//OA 表单处理js工具 2023/10/13 tyc
//**************************************常量************************************************//
const LOCALSTORAGE_KEY_controlDetailPropertity = "LOCALSTORAGE_KEY_controlDetailPropertity";
//******************************************************************************************//
//***********************************IP地址**********************************************//
const CUSTOM_SERVER_PATH = window.location.href;
let ENV_ACTIVE_OA = "DEV";
if(CUSTOM_SERVER_PATH.startsWith("http://xxx")||CUSTOM_SERVER_PATH.startsWith("http://xxx")||CUSTOM_SERVER_PATH.startsWith("https://xxx")||CUSTOM_SERVER_PATH.startsWith("https://xxx")){
    ENV_ACTIVE_OA = "PROD";
}else if (CUSTOM_SERVER_PATH.startsWith("http://xxx")||CUSTOM_SERVER_PATH.startsWith("http://xxx")||CUSTOM_SERVER_PATH.startsWith("https://xxx")){
    ENV_ACTIVE_OA = "DEV";
}
//*****************************************localStorage&sessionStorage*************************//
//*****************************************localStorage&sessionStorage*************************//
//*****************************************缓存管理及页面加载优化start*******************************************************//
(function(window, undefined){
    var config={
        expire : 30,  //缓存数据默认三十分钟失效
        //debug  : false
    }

    function createKey(eventkey,params){
        var baseinfo = WfForm.getBaseInfo();
        if (!validatenull(baseinfo)){
            //return baseinfo.workflowid+"_"+eventkey+"_"+JSON.stringify(params);
            return "OA_cache_form_"+eventkey+"_"+JSON.stringify(params);
        }
    }

    /**
     * 设置缓存的值
     * @param key
     * @param obj
     * @param expire  分钟  过期时间
     */
    function setCache(key,obj,expire){
        var data = JSON.stringify(obj);
        var time = new Date().getTime();
        if (!expire){
            expire = config.expire;
        }
        var jsonData={"data":obj,"cacheTime":time,"expire":expire};
        /*if(config.debug){
            console.log("设置缓存数据："+data);
        }*/
        return localStorage.setItem(key, JSON.stringify(jsonData));
    }

    function setCacheDB(key,obj,expire,callbackSuccess,callbackError){
        var time = new Date().getTime();
        if (!expire){
            expire = config.expire;
        }
        var jsonData={"data":obj,"cacheTime":time,"expire":expire};
        StringUpdate(key, JSON.stringify(jsonData),callbackSuccess,callbackError)
    }

    /**
     * 获取缓存的值
     * @param key
     * @returns {*|string}
     */
    function getCache(key){
        if(!key){
            return "";
        }
        var jsonData=JSON.parse(localStorage.getItem(key));
        if(!jsonData){
            return "";
        }
        var nowDate=new Date().getTime();
        var cacheTime=new Date(jsonData.cacheTime).getTime();
        if(apartMinutes(cacheTime,nowDate)>jsonData.expire){
            localStorage.removeItem(key)
            return "";
        }
        return jsonData.data;
    }

    function getCacheDB(key,callbackSuccess,callbackError){
        if(!key){
            return "";
        }
        StringRead(key,function (data){
            if (validatenull(data)){
                return "";
            }
            var jsonData=JSON.parse(data);
            if(!jsonData){
                return "";
            }
            var nowDate=new Date().getTime();
            var cacheTime=new Date(jsonData.cacheTime).getTime();
            if(apartMinutes(cacheTime,nowDate)>jsonData.expire){
                StringDelete(key);
                return "";
            }
            callbackSuccess(data);
        },callbackError);
    }

    /**
     * 返回JSON格式数据
     * @param key
     * @returns {any|string}
     */
    function getJsonCache(key){
        var jsonStr = getCache(key);
        try{
            return JSON.parse(jsonStr);
        }catch (e){
            return jsonStr;
        }
    }

    function getJsonCacheDB(key,callbackSuccess,callbackError){
        var jsonStr = getCacheDB(key,callbackSuccess,callbackError);
        try{
            return JSON.parse(jsonStr);
        }catch (e){
            return jsonStr;
        }
    }
    //清除缓存
    function clearCache(key){
        if (validatenull(key)){
            // 获取localStorage中所有的键
            const allKeys = Object.keys(localStorage);
        // 筛选出以"OA_cache_form_"开头的键
            const keysToClear = allKeys.filter(k => k.startsWith('OA_cache_form_'));
        // 遍历并清除匹配的项
            keysToClear.forEach(key_ => {
                localStorage.removeItem(key_);
            });
        }else{
            localStorage.removeItem(key);
        }
    }

    function apartMinutes(date1,date2){
        var date3=date2 - date1;
        var minutes=Math.floor(date3/(60*1000));
        /*if(config.debug){
            console.log("数据已缓存时间："+minutes+"分钟");
        }*/
        return minutes;
    }

    var cache =  {
        getCache: getCache,
        getCacheDB:getCacheDB,
        setCacheDB:setCacheDB,
        setCache: setCache,
        createKey:createKey,
        getJsonCache:getJsonCache,
        getJsonCacheDB:getJsonCacheDB,
        clearCache:clearCache,
        configCache: function(obj) {
            $.extend(config, obj);
        }
    };

    window.jQuery && ($.extend(window.jQuery, cache));

})(window);
//*****************************************缓存管理及页面加载优化end*******************************************************//
//*****************************************INDEXDB--start*******************************************************//
let databaseName = "localIndexDB-OA";
let objectT = "OBJECT";
let StringT = "STRING";
let JSONT = "JSON";
let testTag = indexedDB || webkitIndexedDB || mozIndexedDB || null;
let requestINDEXDBOA;
if(testTag){
    requestINDEXDBOA = window.indexedDB.open(databaseName);
}else{
    console.log("不支持INDEXDB");
}
/**
 * db
 */
let db;
/**
 * ======================functions===================
 */
/**
 *
 * @param db
 */
function initTableOA(db) {
    let objectStore;
    if (!db.objectStoreNames.contains(objectT)) {
        objectStore =  db.createObjectStore(
            objectT,
            { autoIncrement: true }
        );
        //objectStore.createIndex('value', 'value', { unique: false });
    }
    let stringStore;
    if (!db.objectStoreNames.contains(StringT)) {
        stringStore =  db.createObjectStore(
            StringT,
            { autoIncrement: true }
        );
        stringStore.createIndex('value', 'value', { unique: false });//字符串打开索引
    }
    let jsonStore;
    if (!db.objectStoreNames.contains(JSONT)) {
        jsonStore =  db.createObjectStore(
            JSONT,
            { autoIncrement: true }
        );
        //JSONT.createIndex('value', 'value', { unique: false });
    }
}

/**
 *
 * @returns {string}
 */
function generateUUID() {
    let d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}


//Object
/**
 *
 * @param key
 * @param value
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function ObjectAdd(key,value,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    let id ;
    if (!validatenull(key)){
        id = key
    }else{
        id = generateUUID();
    }
    const request = db.transaction([objectT], 'readwrite')
        .objectStore(objectT)
        .add(value,key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(id,value);
        }
    };
    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError(id);
        }
        console.log("新增失敗！");
    }
}

/**
 *
 * @param key
 * @param value
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function ObjectUpdate(key,value,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const request = db.transaction([objectT], 'readwrite')
        .objectStore(objectT)
        .put(value,key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(key,value);
        }
    };

    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError(id);
        }
        console.log('数据更新失败');
    }
}

/**
 *
 * @param key
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function ObjectDelete(key,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const request = db.transaction([objectT], 'readwrite')
        .objectStore(objectT)
        .delete(key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess();
        }
    };

    request.onerror = function (event) {
        console.log('数据删除失败');
        if (callbackError instanceof Function){
            callbackError();
        }
    }
}

/**
 *
 * @param key
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function ObjectRead(key,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const transaction = db.transaction([objectT]);
    const objectStore = transaction.objectStore(objectT);
    const request = objectStore.get(key);

    request.onerror = function(event) {
        console.log('事务失败');
        if (callbackError instanceof Function){
            callbackError();
        }
    };
    request.onsuccess = function( event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(request.result);
        }
    };
}

/**
 *
 * @param callbackSuccess
 * @param callbackError
 */
function getAllObject(callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const objectStore = db.transaction(objectT).objectStore(objectT);
    objectStore.openCursor().onsuccess = function (event) {
        const cursor = event.target.result;
        let arr = [];
        if (cursor) {
            const obj = {key:cursor.key,value:cursor.value.value};
            arr.push(obj);
            cursor.continue();
        } else {
            console.log('没有更多数据了！');
        }
        if (callbackSuccess instanceof Function){
            callbackSuccess(arr);
        }
    };
    objectStore.openCursor().onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError();
        }
        console.log("读取数据失败!");
    }

}

//String
/**
 *
 * @param key
 * @param value
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function StringAdd(key,value,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    let id ;
    if (!validatenull(key)){
        id = key
    }else{
        id = generateUUID();
    }
    const request = db.transaction([StringT], 'readwrite')
        .objectStore(StringT)
        .add(value,key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(id,value);
        }
    };
    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError(id);
        }
        console.log("新增失敗！");
    }
}

/**
 *
 * @param key
 * @param value
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function StringUpdate(key,value,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const request = db.transaction([StringT], 'readwrite')
        .objectStore(StringT)
        .put(value,key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(key,value);
        }
    };

    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError(id);
        }
        console.log('数据更新失败');
    }
}

/**
 *
 * @param key
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function StringDelete(key,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const request = db.transaction([StringT], 'readwrite')
        .objectStore(StringT)
        .delete(key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess();
        }
    };

    request.onerror = function (event) {
        console.log('数据删除失败');
        if (callbackError instanceof Function){
            callbackError();
        }
    }
}

/**
 *
 * @param key
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function StringRead(key,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const transaction = db.transaction([StringT]);
    const objectStore = transaction.objectStore(StringT);
    const request = objectStore.get(key);

    request.onerror = function(event) {
        console.log('事务失败');
        if (callbackError instanceof Function){
            callbackError();
        }
    };
    request.onsuccess = function( event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(request.result);
        }
    };
}

/**
 *
 * @param likeStr
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function StringFuzzySearch(likeStr,callbackSuccess,callbackError) {
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const transaction = db.transaction(StringT, "readonly");
    const objectStore = transaction.objectStore(StringT);
    const request = objectStore.openCursor();
    let most = 0;
    let arr = [];
    request.onsuccess = function(event) {
        const cursor = event.target.result;
        if (cursor) {
            if (cursor.value.value.indexOf(likeStr) !== -1&&most<=10) {
                const obj = {key:cursor.key,value:cursor.value.value};
                arr.push(obj);
            }
            cursor.continue();
        }
        if (callbackSuccess instanceof Function){
            callbackSuccess(arr);
        }
    };
    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError();
        }
    }
}

/**
 *
 * @param callbackSuccess
 * @param callbackError
 */
function getAllString(callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const objectStore = db.transaction(StringT).objectStore(StringT);
    objectStore.openCursor().onsuccess = function (event) {
        const cursor = event.target.result;
        let arr = [];
        if (cursor) {
            const obj = {key:cursor.key,value:cursor.value.value};
            arr.push(obj);
            cursor.continue();
        } else {
            console.log('没有更多数据了！');
        }
        if (callbackSuccess instanceof Function){
            callbackSuccess(arr);
        }
    };
    objectStore.openCursor().onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError();
        }
        console.log("读取数据失败!");
    }
}

//JSON
/**
 *
 * @param key
 * @param value
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function JsonAdd(key,value,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    let id ;
    if (!validatenull(key)){
        id = key
    }else{
        id = generateUUID();
    }
    const request = db.transaction([JSONT], 'readwrite')
        .objectStore(JSONT)
        .add(value,key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(id,value);
        }
    };
    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError(id);
        }
        console.log("新增失敗！");
    }
}

/**
 *
 * @param key
 * @param value
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function JsonUpdate(key,value,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const request = db.transaction([JSONT], 'readwrite')
        .objectStore(JSONT)
        .put(value,key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(key,value);
        }
    };

    request.onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError(id);
        }
        console.log('数据更新失败');
    }
}

/**
 *
 * @param key
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function JsonDelete(key,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const request = db.transaction([JSONT], 'readwrite')
        .objectStore(JSONT)
        .delete(key);

    request.onsuccess = function (event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess();
        }
    };

    request.onerror = function (event) {
        console.log('数据删除失败');
        if (callbackError instanceof Function){
            callbackError();
        }
    }
}

/**
 *
 * @param key
 * @param callbackSuccess
 * @param callbackError
 * @constructor
 */
function JsonRead(key,callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const transaction = db.transaction([JSONT]);
    const objectStore = transaction.objectStore(JSONT);
    const request = objectStore.get(key);

    request.onerror = function(event) {
        console.log('事务失败');
        if (callbackError instanceof Function){
            callbackError();
        }
    };
    request.onsuccess = function( event) {
        if (callbackSuccess instanceof Function){
            callbackSuccess(request.result);
        }
    };
}

/**
 *
 * @param callbackSuccess
 * @param callbackError
 */
function getAllJson(callbackSuccess,callbackError){
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    const objectStore = db.transaction(JSONT).objectStore(JSONT);
    objectStore.openCursor().onsuccess = function (event) {
        const cursor = event.target.result;
        let arr = [];
        if (cursor) {
            const obj = {key:cursor.key,value:cursor.value.value};
            arr.push(obj);
            cursor.continue();
        } else {
            console.log('没有更多数据了！');
        }
        if (callbackSuccess instanceof Function){
            callbackSuccess(arr);
        }
    };
    objectStore.openCursor().onerror = function (event) {
        if (callbackError instanceof Function){
            callbackError();
        }
        console.log("读取数据失败!");
    }

}
/**
 * ======================functions===================
 */
requestINDEXDBOA.onsuccess = function (event) {
    db = requestINDEXDBOA.result;
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    initTableOA(db);
    console.log('indexDB opened');
};
requestINDEXDBOA.onerror = function (event) {
    console.log('indexDB opened error');
};
requestINDEXDBOA.onupgradeneeded = function (event) {
    db = event.target.result;
    if (db==null||db==undefined){
        console.error("数据库未初始化或浏览器不支持indexDB");
        return;
    }
    initTableOA(db)
}

//*****************************************INDEXDB--end*******************************************************//
//**************************************业务处理start****************************************//
/**
 * 绑定《主表》字段关系  单个字段
 * @param masterCol  主控制字段名称或id
 * @param slaveCol   被控制字段名称或id
 * @param masterMode  预期值mode  1:非空  2:是数字 3:为指定值后面拼接|val如 3|是 4:包含指定值拼接*val 如4*30  31:主控制字段处于所提供数组内拼接|v1,v2,v3 如 31|1001,1002,1003
 * @param slaveMode   模式 a|b a为预期值情况下的mode b为非预期值的mode ab可选值为 1：只读，2：可编辑，3：必填，4：隐藏字段标签及内容，5:隐藏字段所在行(行内单元格不要存在行合并) 6:必填且只读(对浏览框无效)
 * @param val  赋值
 * @param isInit  是否进行初始化  默认进行初始化
 */
function bindFieldCombine(masterCol,slaveCol,masterMode,slaveMode,val,isInit,callback){
    if (masterCol.indexOf("field")==-1){
        masterCol = WfForm.convertFieldNameToId(masterCol);//将名称转为id
    }
    if (slaveCol.indexOf("field")==-1){
        slaveCol = WfForm.convertFieldNameToId(slaveCol);//将名称转为id
    }
    var slaveModesArr = slaveMode.split("|");
    var pureMasterMode = "";
    var suffixVal = "";
    if (masterMode.indexOf("|")>-1){
        pureMasterMode = masterMode.split("|")[0];
        suffixVal = masterMode.split("|")[1];
    }else if (masterMode.indexOf("*")>-1){
        pureMasterMode = masterMode.split("*")[0];
        suffixVal = masterMode.split("*")[1];
    }else{
        pureMasterMode = masterMode;
    }
    var commonFunc = function (bool,scl,m,val1){
        if (bool){
            setFieldAttrWhenKnowId(scl, m[0]);  //字段属性修改模式
        }else{
            setFieldAttrWhenKnowId(scl, m[1]);  //字段属性修改模式
        }
        var nowVal = WfForm.getFieldValue(scl);
        if (!nowVal){
            if (val1!=null&&val1!=undefined){
                //WfForm.changeFieldValue(scl, {value:val1});//赋值
                setFieldValueOA(scl,val1);
            }else if(val1==""){
                //WfForm.changeFieldValue(scl, {value:""});//赋值
                setFieldValueOA(scl,"");
            }
        }
        if (!validatenull(callback)&&callback instanceof Function){
            callback();
        }
    }
    //执行初始化
    if (isInit){
        var masterColVal = WfForm.getFieldValue(masterCol);
        /*var showValue = WfForm.getBrowserShowName(masterCol);
        if (masterColVal!=showValue){
            masterColVal = showValue;
        }*/
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFunc(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveCol,slaveModesArr,val);
                break;
            case "2":
                commonFunc($.isNumeric(masterColVal),slaveCol,slaveModesArr,val);
                break;
            case "3":
                commonFunc(masterColVal===suffixVal,slaveCol,slaveModesArr,val);
                break;
            case "4":
                commonFunc(masterColVal.indexOf(suffixVal)>-1,slaveCol,slaveModesArr,val);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFunc(contains(arr,masterColVal),slaveCol,slaveModesArr,val);
                break;
            default:
                commonFunc(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveCol,slaveModesArr,val);
                break;
        }

    }
    //执行字段绑定
    WfForm.bindFieldChangeEvent(masterCol, function(obj,id,value){
        /*var showValue = WfForm.getBrowserShowName(masterCol);
        if (value!=showValue){
            value = showValue;
        }*/
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFunc(value!=null&&value!=""&&value!=undefined,slaveCol,slaveModesArr,val);
                break;
            case "2":
                commonFunc($.isNumeric(value),slaveCol,slaveModesArr,val);
                break;
            case "3":
                commonFunc(value===suffixVal,slaveCol,slaveModesArr,val);
                break;
            case "4":
                commonFunc(value.indexOf(suffixVal)>-1,slaveCol,slaveModesArr,val);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFunc(contains(arr,value),slaveCol,slaveModesArr,val);
                break;
            default:
                commonFunc(value==null||value==""||value==undefined,slaveCol,slaveModesArr,val);
                break;
        }
    });
}


/*
var masterInfo = [
    {masterCol:"wlbm",masterMode:"3|xxxx"},
    {masterCol:"scgcnew",masterMode:"3|xxxx"}
]
*/
/**
 * 多个主表控制单个从字段   具体使用方法看上面
 * @param masterInfo
 * @param slaveCol
 * @param slaveMode
 * @param val
 * @param isInit
 * @param callback
 */
function bindFieldCombineWithMasterCols(masterInfo,slaveCol,slaveMode,val,isInit,callback){
    masterInfo.forEach(item=>{
        item.masterCol = getFieldId(item.masterCol);
        var pureMasterMode = "";
        var suffixVal = "";
        if (item.masterMode.indexOf("|")>-1){
            pureMasterMode = item.masterMode.split("|")[0];
            suffixVal = item.masterMode.split("|")[1];
        }else if (item.masterMode.indexOf("*")>-1){
            pureMasterMode = item.masterMode.split("*")[0];
            suffixVal = item.masterMode.split("*")[1];
        }else{
            pureMasterMode = item.masterMode;
        }
        item.pureMasterMode = pureMasterMode;
        item.suffixVal = suffixVal;
    })
    if (slaveCol.indexOf("field")==-1){
        slaveCol = WfForm.convertFieldNameToId(slaveCol);//将名称转为id
    }
    var slaveModesArr = slaveMode.split("|");

    var commonFunc = function (bool,scl,m,val1){
        if (bool){
            setFieldAttrWhenKnowId(scl, m[0]);  //字段属性修改模式
        }else{
            setFieldAttrWhenKnowId(scl, m[1]);  //字段属性修改模式
        }
        var nowVal = WfForm.getFieldValue(scl);
        if (!nowVal){
            if (val1!=null&&val1!=undefined){
                setFieldValueOA(scl,val1);//赋值
            }else if(val1==""){
                setFieldValueOA(scl,"");//赋值
            }
        }
        if (!validatenull(callback)&&callback instanceof Function){
            callback();
        }
    }
    var checkAll = function (masterInfo){
        var res = true;
        masterInfo.forEach(item=>{
            var value1 = WfForm.getFieldValue(item.masterCol);
            switch (item.pureMasterMode){
                case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                    res = res&&(value1!=null&&value1!=""&&value1!=undefined);
                    break;
                case "2":
                    res = res&&$.isNumeric(value1)
                    break;
                case "3":
                    if ($.isNumeric(value1)){
                        res = res&&(value1===item.suffixVal||value1===parseInt(item.suffixVal));
                    }else {
                        res = res&&value1===item.suffixVal
                    }
                    break;
                case "4":
                    res = res&&(value1.indexOf(item.suffixVal)>-1)
                    break;
                case "31":
                    var arr = item.suffixVal.split(",");
                    res = res&&contains(arr,value1);
                    break;
                default:
                    res = res&&(value1==null||value1==""||value1==undefined)
                    break;
            }
        })
        return res;
    }
    //执行初始化
    if (isInit){
       commonFunc(checkAll(masterInfo),slaveCol,slaveModesArr,val)
    }
    //执行字段绑定
     masterInfo.forEach(item=>{
         WfForm.bindFieldChangeEvent(item.masterCol, function(obj,id,value){
             commonFunc(checkAll(masterInfo),slaveCol,slaveModesArr,val);
         });
     })
}

/*var slaveInfoArr = [
    {
        slaveCol:"wlbm",slaveMode:"3|1",val:"1",isInit:false,placeholder:''
    },
    {
        slaveCol:"wlmc",slaveMode:"3|1",val:"1",isInit:false,placeholder:''
    },
    {
        slaveCol:"bb",slaveMode:"3|1",val:"1",isInit:false,placeholder:''
    }
]*/
/**
 * 一个主表字段控制多个字段 批量执行  每个字段属性可单独配置 slaveInfoArr示例如上
 * @param masterCol
 * @param masterMode
 * @param slaveInfoArr
 */
function bindFieldCombineBatch(masterCol,masterMode,slaveInfoArr,callback){
    if (masterCol.indexOf("field")==-1){
        masterCol = WfForm.convertFieldNameToId(masterCol);//将名称转为id
    }
    slaveInfoArr.forEach(item=>{
        if (item.slaveCol.indexOf("field")==-1){
            item.slaveCol = WfForm.convertFieldNameToId(item.slaveCol);//将名称转为id
        }
        var slaveModesArr = item.slaveMode.split("|");
        var a = slaveModesArr[0];
        var b = slaveModesArr[1];
        item.a = a;
        item.b = b;
    });
    var pureMasterMode = "";
    var suffixVal = "";
    if (masterMode.indexOf("|")>-1){
        pureMasterMode = masterMode.split("|")[0];
        suffixVal = masterMode.split("|")[1];
    }else if (masterMode.indexOf("*")>-1){
        pureMasterMode = masterMode.split("*")[0];
        suffixVal = masterMode.split("*")[1];
    }else{
        pureMasterMode = masterMode;
    }
    var commonFuncInit = function (bool,slaveInfoArr,isFlag){
        if (bool){
            slaveInfoArr.forEach(item=>{
                if (item.isInit||isFlag){
                    setFieldAttrWhenKnowId(item.slaveCol, item.a);  //字段属性修改模式
                    var nowVal = WfForm.getFieldValue(item.slaveCol);
                    if (!nowVal){
                        if (item.val!=null&&item.val!=undefined){
                            setFieldValueOA(item.slaveCol,item.val);//赋值
                        }else if(item.val==""){
                            setFieldValueOA(item.slaveCol,"");//赋值
                        }
                    }
                    if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                        WfForm.setTextFieldEmptyShowContent(item.slaveCol,  item.placeholder);
                    }
                    if (!validatenull(callback)&&callback instanceof Function){
                        callback();
                    }
                }
            })
        }else{
            slaveInfoArr.forEach(item=>{
                if (item.isInit||isFlag){
                    setFieldAttrWhenKnowId(item.slaveCol, item.b);  //字段属性修改模式
                    var nowVal = WfForm.getFieldValue(item.slaveCol);
                    if (!nowVal){
                        if (item.val!=null&&item.val!=undefined){
                            WfForm.changeFieldValue(item.slaveCol, {value:item.val});//赋值
                        }else if(item.val==""){
                            WfForm.changeFieldValue(item.slaveCol, {value:""});//赋值
                        }
                    }
                    if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                        WfForm.setTextFieldEmptyShowContent(item.slaveCol,  item.placeholder);
                    }
                    if (!validatenull(callback)&&callback instanceof Function){
                        callback();
                    }
                }
            })
        }
    }
        //执行初始化
        var masterColVal = WfForm.getFieldValue(masterCol);
        var showValue = WfForm.getBrowserShowName(masterCol);
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFuncInit(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveInfoArr,false);
                break;
            case "2":
                commonFuncInit($.isNumeric(masterColVal),slaveInfoArr,false);
                break;
            case "3":
                commonFuncInit(masterColVal===suffixVal,slaveInfoArr,false);
                break;
            case "4":
                commonFuncInit(masterColVal.indexOf(suffixVal)>-1,slaveInfoArr,false);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFuncInit(contains(arr,masterColVal),slaveInfoArr,false);
                break;
            default:
                commonFuncInit(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveInfoArr,false);
                break;
        }
    //执行字段绑定
    WfForm.bindFieldChangeEvent(masterCol, function(obj,id,value){
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFuncInit(value!=null&&value!=""&&value!=undefined,slaveInfoArr,true);
                break;
            case "2":
                commonFuncInit($.isNumeric(value),slaveInfoArr,true);
                break;
            case "3":
                commonFuncInit(value===suffixVal,slaveInfoArr,true);
                break;
            case "4":
                commonFuncInit(value.indexOf(suffixVal)>-1,slaveInfoArr,true);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFuncInit(contains(arr,value),slaveInfoArr,false);
                break;
            default:
                commonFuncInit(value==null||value==""||value==undefined,slaveInfoArr,true);
                break;
        }
    });
}

/*var slaveInfoArr = [
    {
        detailNumber:"1",slaveCol:"wlbm",slaveMode:"3|1",val:"1,2,3",isInit:false,index:"0,1,2",placeholder:''
    },
    {
        detailNumber:"2",slaveCol:"wlmc",slaveMode:"3|1",val:"1",isInit:false,index:"all",placeholder:''
    },
    {
        detailNumber:"1",slaveCol:"bb",slaveMode:"3|1",val:"1",isInit:false,index:"all",placeholder:''
    },
    {
        detailNumber:"1",slaveCol:"xx",slaveMode:"3|1",isInit:false,index:"all",placeholder:''
    }
]*/

/**
 * 《主表》字段控制明细表字段
 * @param masterCol  主表字段名称或id
 * @param masterMode  主表模式 预期值mode  1:非空  2:是数字 3:为指定值后面拼接|val如 3|是 4:包含指定值拼接*val 如4*30
 * @param slaveInfoArr  如上detailNumber为明细表代号 如1 slaveCol为明细表id或名称  slaveMode、val、isInit见bindFieldCombine的slaveMode解释
 */
function bindFieldDetailCombine(masterCol,masterMode,slaveInfoArr,callback){
    if (masterCol.indexOf("field")==-1){
        masterCol = WfForm.convertFieldNameToId(masterCol);//将名称转为id
    }
    var detailArr = [];//存储明细表序号 如['1','2'] 不重复
    slaveInfoArr.forEach(item=>{
        if (detailArr.indexOf(item.detailNumber)==-1){
            detailArr.push(item.detailNumber);
        }
        item.detailNumber = "detail_"+item.detailNumber;
        if (item.slaveCol.indexOf("field")==-1){
            item.slaveCol = WfForm.convertFieldNameToId(item.slaveCol,item.detailNumber);//将名称转为id
        }
        var slaveModesArr = item.slaveMode.split("|");
        var a = slaveModesArr[0];
        var b = slaveModesArr[1];
        item.a = a;
        item.b = b;
        if (item.index!=null&&item.index!=""&&item.index!=undefined){
            if (item.index==="all"){
                item.isAll = true;
            }else{
                item.isAll = false;
                item.indexArr = item.index.split(",");
                for(var i=0;i<item.indexArr.length;i++){
                    item.indexArr[i] = item.indexArr[i]-1;//行数减一获得数组index
                }
            }
        }else{
            item.isAll = true;
        }
    });
    var pureMasterMode = "";
    var suffixVal = "";
    if (masterMode.indexOf("|")>-1){
        pureMasterMode = masterMode.split("|")[0];
        suffixVal = masterMode.split("|")[1];
    }else if (masterMode.indexOf("*")>-1){
        pureMasterMode = masterMode.split("*")[0];
        suffixVal = masterMode.split("*")[1];
    }else{
        pureMasterMode = masterMode;
    }

    var commonFunc = function (bool,slaveInfoArr,isFlag,index){
        if (bool){
            slaveInfoArr.forEach(item=>{
                if (item.isInit||isFlag){
                   if (item.isAll){//改变该明细表所有行此字段的属性和值
                       var indexs = WfForm.getDetailAllRowIndexStr(item.detailNumber).split(",");
                       indexs.forEach(itemInner=>{
                           setFieldAttrWhenKnowId(item.slaveCol+"_"+itemInner, item.a);  //字段属性修改模式
                           var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+itemInner);
                           if (!nowVal){ //当前没有值才赋值  否则保持原值
                               if (item.val!=null&&item.val!=undefined){
                                   //WfForm.changeFieldValue(item.slaveCol+"_"+itemInner, {value:item.val});//赋值
                                   setFieldValueOA(item.slaveCol,item.val,itemInner);//赋值
                               }else if(item.val==""){
                                   setFieldValueOA(item.slaveCol,"",itemInner);//赋值
                               }
                           }
                           if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                               WfForm.setTextFieldEmptyShowContent(item.slaveCol+"_"+itemInner,  item.placeholder);
                           }
                       })
                   }else{//只改变指定rowIndex的属性和值
                       var indexArr = item.indexArr;
                       var indexs = WfForm.getDetailAllRowIndexStr(item.detailNumber).split(",")
                       var j = 0;
                       var tempArr = [];
                       indexArr.forEach(itemInner=>{
                           setFieldAttrWhenKnowId(item.slaveCol+"_"+indexs[parseInt(itemInner)], item.a);  //字段属性修改模式
                           var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+indexs[parseInt(itemInner)]);
                           if (!nowVal){  //当前没有值才赋值  否则保持原值
                               if (item.val!=null&&item.val!=undefined){
                                   tempArr = item.val.split(",");
                                   if (item.val.length==1){
                                       //WfForm.changeFieldValue(item.slaveCol+"_"+indexs[parseInt(itemInner)], {value:tempArr[0]});//赋值
                                       setFieldValueOA(item.slaveCol,tempArr[0],indexs[parseInt(itemInner)]);//赋值
                                   }else{
                                       //WfForm.changeFieldValue(item.slaveCol+"_"+indexs[parseInt(itemInner)], {value:tempArr[j]});//赋值
                                       setFieldValueOA(item.slaveCol,tempArr[j],indexs[parseInt(itemInner)]);//赋值
                                   }
                               }
                           }
                           j++;
                           if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                               WfForm.setTextFieldEmptyShowContent(item.slaveCol+"_"+indexs[parseInt(itemInner)],  item.placeholder);
                           }
                       })
                   }
                    if (!validatenull(callback)&&callback instanceof Function){
                        callback();
                    }
                }
            })
        }else{
            slaveInfoArr.forEach(item=>{
                if (item.isInit||isFlag){
                    if (item.isAll){//改变该明细表所有行此字段的属性和值
                        var indexs = WfForm.getDetailAllRowIndexStr(item.detailNumber).split(",");
                        indexs.forEach(itemInner=>{
                            setFieldAttrWhenKnowId(item.slaveCol+"_"+itemInner, item.b);  //字段属性修改模式
                            var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+itemInner);
                            if (!nowVal){
                                if (item.val!=null&&item.val!=undefined){
                                    item.val = item.val.split(",")[0];
                                    //WfForm.changeFieldValue(item.slaveCol+"_"+itemInner, {value:item.val});//赋值
                                    setFieldValueOA(item.slaveCol,item.val,itemInner)
                                }else if(item.val==""){
                                    //WfForm.changeFieldValue(item.slaveCol+"_"+itemInner, {value:""});//赋值
                                    setFieldValueOA(item.slaveCol,"",itemInner)
                                }
                            }
                            if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                                WfForm.setTextFieldEmptyShowContent(item.slaveCol+"_"+itemInner,  item.placeholder);
                            }
                        })
                    }else{//只改变指定rowIndex的属性和值
                        var indexArr = item.indexArr;
                        var indexs = WfForm.getDetailAllRowIndexStr(item.detailNumber).split(",")
                        var j = 0;
                        var tempArr = [];
                        indexArr.forEach(itemInner=>{
                            setFieldAttrWhenKnowId(item.slaveCol+"_"+indexs[parseInt(itemInner)], item.b);  //字段属性修改模式
                            var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+indexs[parseInt(itemInner)]);
                            if (!nowVal){
                                if (item.val!=null&&item.val!=undefined){
                                    tempArr = item.val.split(",");
                                    if (item.val.length==1){
                                        //WfForm.changeFieldValue(item.slaveCol+"_"+indexs[parseInt(itemInner)], {value:tempArr[0]});//赋值
                                        setFieldValueOA(item.slaveCol,tempArr[0],indexs[parseInt(itemInner)])
                                    }else{
                                        //WfForm.changeFieldValue(item.slaveCol+"_"+indexs[parseInt(itemInner)], {value:tempArr[j]});//赋值
                                        setFieldValueOA(item.slaveCol,tempArr[j],indexs[parseInt(itemInner)])
                                    }
                                }
                            }
                            j++;
                            if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                                WfForm.setTextFieldEmptyShowContent(item.slaveCol+"_"+indexs[parseInt(itemInner)],  item.placeholder);
                            }
                        })
                    }
                    if (!validatenull(callback)&&callback instanceof Function){
                        callback();
                    }
                }
            })
        }
    }

    //执行初始化
    var masterColVal = WfForm.getFieldValue(masterCol);
    switch (pureMasterMode){
        case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
            commonFunc(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveInfoArr,false);
            break;
        case "2":
            commonFunc($.isNumeric(masterColVal),slaveInfoArr,false);
            break;
        case "3":
            commonFunc(masterColVal===suffixVal,slaveInfoArr,false);
            break;
        case "4":
            commonFunc(masterColVal.indexOf(suffixVal)>-1,slaveInfoArr,false);
            break;
        case "31":
            var arr = suffixVal.split(",");
            commonFunc(contains(arr,masterColVal),slaveInfoArr,false);
            break;
        default:
            commonFunc(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveInfoArr,false);
            break;
    }

    //执行主键字段改变事件绑定
    WfForm.bindFieldChangeEvent(masterCol, function(obj,id,value){
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFunc(value!=null&&value!=""&&value!=undefined,slaveInfoArr,true);
                break;
            case "2":
                commonFunc($.isNumeric(value),slaveInfoArr,true);
                break;
            case "3":
                commonFunc(value===suffixVal,slaveInfoArr,true);
                break;
            case "4":
                commonFunc(value.indexOf(suffixVal)>-1,slaveInfoArr,true);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFunc(contains(arr,value),slaveInfoArr,true);
                break;
            default:
                commonFunc(value==null||value==""||value==undefined,slaveInfoArr,true);
                break;
        }
    });
    //明细表改变事件绑定
    detailArr.forEach(item=>{
        WfForm.registerAction(WfForm.ACTION_ADDROW+item, function(index){
            masterColVal = WfForm.getFieldValue(masterCol);
            switch (pureMasterMode){
                case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                    commonFunc(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveInfoArr,false,index);
                    break;
                case "2":
                    commonFunc($.isNumeric(masterColVal),slaveInfoArr,false,index);
                    break;
                case "3":
                    commonFunc(masterColVal===suffixVal,slaveInfoArr,false,index);
                    break;
                case "4":
                    commonFunc(masterColVal.indexOf(suffixVal)>-1,slaveInfoArr,false,index);
                    break;
                case "31":
                    var arr = suffixVal.split(",");
                    commonFunc(contains(arr,masterColVal),slaveInfoArr,false,index)
                    break;
                default:
                    commonFunc(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveInfoArr,false,index);
                    break;
            }
        });
        WfForm.registerAction(WfForm.ACTION_DELROW+item, function(arg){
            masterColVal = WfForm.getFieldValue(masterCol);
            switch (pureMasterMode){
                case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                    commonFunc(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveInfoArr,false);
                    break;
                case "2":
                    commonFunc($.isNumeric(masterColVal),slaveInfoArr,false);
                    break;
                case "3":
                    commonFunc(masterColVal===suffixVal,slaveInfoArr,false);
                    break;
                case "4":
                    commonFunc(masterColVal.indexOf(suffixVal)>-1,slaveInfoArr,false);
                    break;
                case "31":
                    var arr = suffixVal.split(",");
                    commonFunc(contains(arr,masterColVal),slaveInfoArr,false)
                    break;
                default:
                    commonFunc(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveInfoArr,false);
                    break;
            }
        });
    })
}


/*var slaveInfoArr = [
    {
        slaveCol:"sl",slaveMode:"3|1",val:111,isInit:true,placeholder:''
    },
    {
        slaveCol:"bb",slaveMode:"3|1",val:"啦啦啦",isInit:true,placeholder:''
    }
]*/
/**
 * 明细表字段绑定监听事件
 * @param detailNumber  明细表号码
 * @param masterCol   主控制字段名称或id
 * @param masterMode  主控制字段预期值mode  1:非空  2:是数字 3:为指定值后面拼接|val如 3|是 4:包含指定值拼接*val 如4*30
 * @param slaveInfoArr  如上detailNumber为明细表代号 如1 slaveCol为明细表id或名称  slaveMode、val、isInit见bindFieldCombine的slaveMode解释 * @param val
 * @param useShowVal 默认为false 可不填  标识是否取用主控字段的表显值而不是实际值  如浏览框显示高测科技股份有限公司  实际值为公司代码
 */
function bindDetailEachOther(detailNumber,masterCol,masterMode,slaveInfoArr,useShowVal){
    detailNumber = detailNumber.toString();
    if (detailNumber.indexOf("detail_")==-1){
        detailNumber = "detail_"+detailNumber;
    }
    if (masterCol.indexOf("field")==-1){
        masterCol = WfForm.convertFieldNameToId(masterCol,detailNumber);//将名称转为id
    }
    slaveInfoArr.forEach(item=>{
         if (item.slaveCol.indexOf("field")==-1){
             item.slaveCol = WfForm.convertFieldNameToId(item.slaveCol,detailNumber);
         }
        item.a = item.slaveMode.split("|")[0];
        item.b = item.slaveMode.split("|")[1];
    })
    var pureMasterMode = "";
    var suffixVal = "";
    if (masterMode.indexOf("|")>-1){
        pureMasterMode = masterMode.split("|")[0];
        suffixVal = masterMode.split("|")[1];
    }else if (masterMode.indexOf("*")>-1){
        pureMasterMode = masterMode.split("*")[0];
        suffixVal = masterMode.split("*")[1];
    }else{
        pureMasterMode = masterMode;
    }

    var commonFuncInit = function (bool,slaveInfoArr,index){
        if (bool){
            slaveInfoArr.forEach(item=>{
                setFieldAttrWhenKnowId(item.slaveCol+"_"+index, item.a);  //字段属性修改模式
                var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+index);
                if (!nowVal){
                    if (item.val!=null&&item.val!=undefined&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:item.val});//赋值
                        setFieldValueOA(item.slaveCol,item.val,index);
                    }else if(item.val==""&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:""});//赋值
                        setFieldValueOA(item.slaveCol,"",index);
                    }
                }
                if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                    WfForm.setTextFieldEmptyShowContent(item.slaveCol+"_"+index,  item.placeholder);//设置placeholder
                }
            });
        }else{
            slaveInfoArr.forEach(item=>{
                setFieldAttrWhenKnowId(item.slaveCol+"_"+index, item.b);  //字段属性修改模式
                var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+index);
                if (!nowVal){
                    if (item.val!=null&&item.val!=undefined&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:item.val});//赋值
                        setFieldValueOA(item.slaveCol,item.val,index);
                    }else if(item.val==""&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:""});//赋值
                        setFieldValueOA(item.slaveCol,"",index);
                    }
                }
                if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                    WfForm.setTextFieldEmptyShowContent(item.slaveCol+"_"+index,  item.placeholder);//设置placeholder
                }
            });
        }
    }

    var commonFunc = function (bool,slaveInfoArr,index){
        if (bool){
            slaveInfoArr.forEach(item=>{
                WfForm.changeFieldAttr(item.slaveCol+"_"+index, item.a);  //字段属性修改模式
                var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+index);
                if (!nowVal){
                    if (item.val!=null&&item.val!=undefined&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:item.val});//赋值
                        setFieldValueOA(item.slaveCol,item.val,index);
                    }else if(item.val==""&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:""});//赋值
                        setFieldValueOA(item.slaveCol,"",index);
                    }
                }
                if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                    WfForm.setTextFieldEmptyShowContent(item.slaveCol,  item.placeholder);
                }
            })
        }else{
            slaveInfoArr.forEach(item=>{
                setFieldAttrWhenKnowId(item.slaveCol+"_"+index, item.b);  //字段属性修改模式
                var nowVal = WfForm.getFieldValue(item.slaveCol+"_"+index);
                if (!nowVal){
                    if (item.val!=null&&item.val!=undefined&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:item.val});//赋值
                        setFieldValueOA(item.slaveCol,item.val,index);
                    }else if(item.val==""&&item.isInit){
                        //WfForm.changeFieldValue(item.slaveCol+"_"+index, {value:""});//赋值
                        setFieldValueOA(item.slaveCol,"",index);
                    }
                }
                if (item.placeholder!=null&&item.placeholder!=undefined&&item.placeholder!=""){
                    WfForm.setTextFieldEmptyShowContent(item.slaveCol,  item.placeholder);
                }
            })
        }
    }

    var checkVal = function (val2,val3){
        var b2 = val2!=null&&val2!=""&&val2!=undefined;
        var b3 = val3!=null&&val3!=""&&val3!=undefined;
        if (b2&&!b3){
            return val2
        }else if (!b2&&b3){
            return val3;
        }
    }
    //执行初始化
    //获取当前明细表所有下标数组
    var indexArr = WfForm.getDetailAllRowIndexStr(detailNumber);
    if (indexArr===""){
        indexArr = [];
    }else{
        indexArr = indexArr.split(",")
    }
    indexArr.forEach(item=>{//初始化
        var masterColVal = WfForm.getFieldValue(masterCol+"_"+item);
        if (useShowVal){//使用表单显示的值
            var masterColBrowserVal = WfForm.getBrowserShowName(masterCol+"_"+item);  //因为无法判断是那种类型组件 所以先都取出来
            var masterColSelectVal = WfForm.getSelectShowName(masterCol+"_"+item);
            masterColVal = checkVal(masterColBrowserVal,masterColSelectVal);
        }
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFuncInit(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveInfoArr,item);
                break;
            case "2":
                commonFuncInit($.isNumeric(masterColVal),slaveInfoArr,item);
                break;
            case "3":
                commonFuncInit(masterColVal===suffixVal,slaveInfoArr,item);
                break;
            case "4":
                commonFuncInit(masterColVal.indexOf(suffixVal)>-1,slaveInfoArr,item);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFuncInit(contains(arr,masterColVal),slaveInfoArr,item)
                break;
            default:
                commonFuncInit(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveInfoArr,item);
                break;
        }

    });

    WfForm.bindDetailFieldChangeEvent(masterCol,function(id,rowIndex,value){//绑定主字段变化事件
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFunc(value!=null&&value!=""&&value!=undefined,slaveInfoArr,rowIndex);
                break;
            case "2":
                commonFunc($.isNumeric(value),slaveInfoArr,rowIndex);
                break;
            case "3":
                commonFunc(value===suffixVal,slaveInfoArr,rowIndex);
                break;
            case "4":
                commonFunc(value.indexOf(suffixVal)>-1,slaveInfoArr,rowIndex);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFunc(contains(arr,value),slaveInfoArr,rowIndex)
                break;
            default:
                commonFunc(value==null||value==""||value==undefined,slaveInfoArr,rowIndex);
                break;
        }
    });

    WfForm.registerAction(WfForm.ACTION_ADDROW+detailNumber.replace("detail_",""), function(item){
        var masterColVal = WfForm.getFieldValue(masterCol+"_"+item);
        if (useShowVal){//使用表单显示的值
            var masterColBrowserVal = WfForm.getBrowserShowName(masterCol+"_"+item);  //因为无法判断是那种类型组件 所以先都取出来
            var masterColSelectVal = WfForm.getSelectShowName(masterCol+"_"+item);
            masterColVal = checkVal(masterColBrowserVal,masterColSelectVal);
        }
        switch (pureMasterMode){
            case "1": //当pureMasterMode符合预期时改变slaveCol的属性和值
                commonFunc(masterColVal!=null&&masterColVal!=""&&masterColVal!=undefined,slaveInfoArr,item);
                break;
            case "2":
                commonFunc($.isNumeric(masterColVal),slaveInfoArr,item);
                break;
            case "3":
                commonFunc(masterColVal===suffixVal,slaveInfoArr,item);
                break;
            case "4":
                commonFunc(masterColVal.indexOf(suffixVal)>-1,slaveInfoArr,item);
                break;
            case "31":
                var arr = suffixVal.split(",");
                commonFunc(contains(arr,masterColVal),slaveInfoArr,item)
                break;
            default:
                commonFunc(masterColVal==null||masterColVal==""||masterColVal==undefined,slaveInfoArr,item);
                break;
        }
    });
}

/**
 * 添加自定义按钮和事件
 * @param btName
 * @param callbackName
 */
function addButton(btName,callbackName){
    if (!contains(callbackName,"(")&&!contains(callbackName,")")){
        callbackName = callbackName + "()";
    }
    var printButton = "<span style='display: inline-block; line-height: 28px; vertical-align: middle; margin-left: 10px;'><button  title='"+btName+"' type='button' class='ant-btn ant-btn-primary' onclick='"+callbackName+"'><div class='wf-req-top-button'>"+btName+"</div></button></span>"
    $($($("div[ecid='undefined_div@qu6vnd']").find("div[ecid='undefined_div@qjebvs']")[2].children[0])[0].children[0]).append($(printButton))
}

/**
 * 获取明细行行下标数组
 * @param detailNumber  明细表号码
 * @returns {array}  明细行行下标数组
 */
function getRowIndexStr(detailNumber,onlyShow){
    if (validatenull(onlyShow)){
        onlyShow = false;
    }
    if (onlyShow){
        var hidetrs = $('.interface_hide');
        var rows = WfForm.getDetailAllRowIndexStr("detail_"+detailNumber);
        if (!validatenull(rows)){
            rows =  rows.split(",");
        }else{
            rows = [];
        }
        var obj = {show:[],hide:[]}
        for(var i=0;i<hidetrs.length;i++){
            obj.hide.push($(hidetrs[i]).attr("data-rowindex"))
            if (rows.indexOf($(hidetrs[i]).attr("data-rowindex"))>-1){
                rows.splice(rows.indexOf($(hidetrs[i]).attr("data-rowindex")),1);
            }
        }
        obj.show = rows;
        return obj;
    }else{
        var rows = WfForm.getDetailAllRowIndexStr("detail_"+detailNumber);
        if (!validatenull(rows)){
            return rows.split(",");
        }else{
            return [];
        }
    }
}

/**
 * 获取明细表detailNumber的数据  json格式   detailNumber、isCheck都不填取第一个明细表的所有行数据
 * @param detailNumber   明细表号码
 * @param isCheck   是否是获取选中的数据  不填默认获取全部行
 * @returns {array} 获取明细表detailNumber的数据  json格式
 */
function getRowsDataOA(detailNumber,isCheck){
    if (validatenull(detailNumber)){
        detailNumber = 1;
    }else{
        detailNumber = parseInt(detailNumber);
    }
    var rows = getRowIndexStr(detailNumber);
    if (isCheck){
        rowStr = WfForm.getDetailCheckedRowIndexStr("detail_"+detailNumber);
        if (validatenull(rowStr)){
            msgBox("未选择明细表"+detailNumber+"的任何行")
            return {};
        }else {
            rows = rowStr.split(",");
        }
    }
    var items = [];
    var itemModel = {};
    var tds = $($('#oTable'+(detailNumber-1)).find("tr.detail_data_row")[0]).find("td");
    for(var i=0;i<tds.length;i++){
        var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
        if (!validatenull(fieldname)){
            itemModel[fieldname] = "";
        }
    }
    for(var i=0;i<rows.length;i++){
        var tempItem = {};
        Object.assign(tempItem,itemModel);//这里需要用深拷贝
        Object.keys(tempItem).forEach(key=>{
            tempItem[key] = getFieldValue(getFieldId(key,true,detailNumber)+"_"+rows[i]);
        })
        items.push(tempItem)
    }
    return items;
}
var getCamelCharsOA = function(chinese){
    pinyinPro.customPinyin({'调':'diao'})
    if (validatenull(chinese)){
        return "";
    }
    var allStr = pinyinPro.pinyin(chinese, { toneType: 'none' }).replaceAll(/[^A-Za-z0-9\s]/g, '').replaceAll('  ',' ');;
    var resStr = "";
    var arr = allStr.split(" ");
    for(var x=0;x<arr.length;x++){
        resStr += arr[x].substring(0,1).toLowerCase()
    }
    return resStr;
}
/**
 * 获取明细表的表头信息数组
 * @param detailNumber   明细表号码
 * @param isShowHide   是否包含隐藏列  true包含 false不包含
 * @returns {array}  获取明细表的表头信息数组
 */
function getTitleInfo(detailNumber,isShowHide){
    var resarray = [];
    var cellmark_ = "detail_"+detailNumber+"_3_";
    var spans = "";
    var rows = getRowIndexStr(detailNumber)
    if (rows.length==0){
        if (isShowHide){
            var span1 = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[1]).find("td.etype_2").find('span');
            spans = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[2]).find("td.etype_2").find('span');
            if (span1.length!=0){
                spans = span1
            }
            for(var i=0;i<spans.length;i++){
                resarray.push(spans[i].textContent+"-"+getCamelCharsOA(spans[i].textContent))
            }
            return resarray;
        }else{
            var tds = $('#oTable'+(parseInt(detailNumber)-1)).find("tr.detail_data_row").find('td.etype_3');
            var span1 = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[1]).find("td.etype_2").find('span');
            spans = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[2]).find("td.etype_2").find('span');
            if (span1.length!=0){
                spans = span1
            }
            for(var i=0;i<spans.length;i++){
                if(!$(tds[i]).hasClass("detail_hide_col")){
                    var newcellmark =cellmark_+(i+2);
                    resarray.push(spans[i].textContent+"-"+getCamelCharsOA(spans[i].textContent))
                }
            }
            return  resarray;
        }
    }else{
        if (isShowHide){
            var span1 = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[1]).find("td.etype_2").find('span');
            spans = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[2]).find("td.etype_2").find('span');
            if (span1.length!=0){
                spans = span1
            }
            for(var i=0;i<spans.length;i++){
                var newcellmark =cellmark_+(i+2);
                resarray.push(spans[i].textContent+"-"+$("div[data-cellmark="+newcellmark+"]").attr("data-fieldname"))
            }
            return resarray;
        }else{
            var tds = $('#oTable'+(parseInt(detailNumber)-1)).find("tr.detail_data_row").find('td.etype_3');
            var span1 = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[1]).find("td.etype_2").find('span');
            spans = $($('#oTable'+(parseInt(detailNumber)-1)).find('tr')[2]).find("td.etype_2").find('span');
            if (span1.length!=0){
                spans = span1
            }
            for(var i=0;i<spans.length;i++){
                if(!$(tds[i]).hasClass("detail_hide_col")){
                    var newcellmark =cellmark_+(i+2);
                    resarray.push(spans[i].textContent+"-"+$("div[data-cellmark="+newcellmark+"]").attr("data-fieldname"))
                }
            }
            return  resarray;
        }
    }
}
var OA_TITLE_YS_INFO = {};

/**
 * 修改明细表列名
 * @param col   列字段名
 * @param title  要修改成的内容  不写则修改为原名称
 * @param detailNumber  明细表号码  不填默认取第一个存在字段col的明细表
 * 示例：
 * 如明细表1中存在字段物料编码字段 字段名为wlbm 中文名为物料编码  现想将其改为商品编码则执行
 * setDetailTitle('wlbm','商品编码')   其中detailNumber没有填因为是第一个明细表  如果存在多个明细表字段名重名的情况下 而且取的不是第一个明细表的字段那么就需要指定detailNumber
 如果想重置为原值则直接执行setDetailTitle('wlbm')即可
 */
function setDetailTitle(col,title,detailNumber){
    var json = getFieldIdAndDetail(col,detailNumber);
    var tableInfo = OA_TITLE_YS_INFO[json.detailNumber];
    var colInfo;
    if (!validatenull(tableInfo)){
        colInfo = OA_TITLE_YS_INFO[json.detailNumber][col];
    }
    if (validatenull(colInfo)){
        var info = WfForm.getFieldInfo(getFieldId(col,false,json.detailNumber))
        var span = $('#oTable'+(parseInt(json.detailNumber)-1)).find("span:contains('"+info.fieldlabel+"')")
            .filter(function() {
                return $(this).text().trim() === info.fieldlabel.trim();
            });
        var cellmark = $(span).parent().attr("data-cellmark");
        $(span).text(title)
        colInfo = {};
        colInfo["cellmark"] = cellmark;
        colInfo["title"] = title;
        if (validatenull( OA_TITLE_YS_INFO[json.detailNumber])){
            OA_TITLE_YS_INFO[json.detailNumber] = {};
        }
        OA_TITLE_YS_INFO[json.detailNumber][col] = colInfo;
    }else{
        if (validatenull(title)){
            var info = WfForm.getFieldInfo(getFieldId(col,false,json.detailNumber));
            title = info.fieldlabel;
        }
        var cellmark = colInfo["cellmark"];
        colInfo["title"] = title;
        $("div[data-cellmark='"+cellmark+"']").find("span").text(title)
        OA_TITLE_YS_INFO[json.detailNumber][col] = colInfo;
    }
}

/**
 * 获取明细表数据  可以标识出不同类型字段
 * @param detailNumber
 * @param indexs   行标识数组  意思是只获取这些行的数据
 * @returns {array}  获取明细表数据
 */
function getRowsDataOAWithIndexs(detailNumber,indexs){
    if (validatenull(detailNumber)){
        detailNumber = 1;
    }else{
        detailNumber = parseInt(detailNumber);
    }
    var rows = indexs;
    var items = [];
    var itemModel = {};
    var tds = $($('#oTable'+(detailNumber-1)).find("tr.detail_data_row")[0]).find("td");
    for(var i=0;i<tds.length;i++){
        var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
        if (!validatenull(fieldname)){
            itemModel[fieldname] = "";
        }
    }
    for(var i=0;i<rows.length;i++){
        var tempItem = {};
        Object.assign(tempItem,itemModel);//这里需要用深拷贝
        Object.keys(tempItem).forEach(key=>{
            tempItem[key] = getFieldValue(getFieldId(key,true,detailNumber)+"_"+rows[i]);
        })
        items.push(tempItem)
    }
    return items;
}

/**
 * 获取明细表显示值数组
 * @param detailNumber
 * @param isCheck  是否只选择checkbox选中的行
 */
function getRowsShowDatas(detailNumber,isCheck){
    if (validatenull(detailNumber)){
        detailNumber = 1;
    }
    var rows = getRowIndexStr(detailNumber);
    if (isCheck){
        rowStr = WfForm.getDetailCheckedRowIndexStr("detail_"+detailNumber);
        if (validatenull(rowStr)){
            msgBox("未选择明细表"+detailNumber+"的任何行")
            return {};
        }else {
            rows = rowStr.split(",");
        }
    }
    var items = [];
    var itemModel = {};
    var tds = $($('#oTable'+(detailNumber-1)).find("tr.detail_data_row")[0]).find("td");
    for(var i=0;i<tds.length;i++){
        var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
        if (validatenull(fieldname)){
            continue;
        }
        if (!validatenull(fieldname)){
            itemModel[fieldname] = "";
        }
    }
    for(var i=0;i<rows.length;i++){
        var tempItem = {};
        Object.assign(tempItem,itemModel);//这里需要用深拷贝
        Object.keys(tempItem).forEach(key=>{
            var showName = getShowNameOA(key,rows[i],detailNumber);
            tempItem[key] = showName;
        })
        items.push(tempItem)
    }
    return items;
}
/**
 * 获取明细表数据  可以标识出不同类型字段
 * @param detailNumber
 * @param isCheck
 * @returns {{}|*[]}
 */
function getRowsDataExtraOA(detailNumber,isCheck){
    if (validatenull(detailNumber)){
        detailNumber = 1;
    }
    var rows = getRowIndexStr(detailNumber);
    if (isCheck){
        rowStr = WfForm.getDetailCheckedRowIndexStr("detail_"+detailNumber);
        if (validatenull(rowStr)){
            msgBox("未选择明细表"+detailNumber+"的任何行")
            return {};
        }else {
            rows = rowStr.split(",");
        }
    }
    var items = [];
    var itemModel = {};
    var tds = $($('#oTable'+(detailNumber-1)).find("tr.detail_data_row")[0]).find("td");
    for(var i=0;i<tds.length;i++){
        var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
        if (validatenull(fieldname)){
            continue;
        }
        var fieldInfo = WfForm.getFieldInfo(getFieldId(fieldname,false,detailNumber));
        if (fieldInfo.hasOwnProperty("browserattr")){
            fieldname  = "_"+fieldname;
        }
        if (!validatenull(fieldname)){
            itemModel[fieldname] = "";
        }
    }
    for(var i=0;i<rows.length;i++){
        var tempItem = {};
        Object.assign(tempItem,itemModel);//这里需要用深拷贝
        Object.keys(tempItem).forEach(key=>{
            if (contains(key,"_")){
                var _key = key.replace("_","");
                var showName = getShowNameOA(_key,rows[i],detailNumber);
                var val = getFieldValue(_key,rows[i],detailNumber);
                if (validatenull(showName)&&validatenull(val)){
                    tempItem[key] = "";
                }else{
                    tempItem[key] = val+"|"+showName;
                }
            }else{
                var _key = key.replace("_","");
                tempItem[key] = getFieldValue(_key,rows[i],detailNumber);
            }
        })
        items.push(tempItem)
    }
    return items;
}

/**
 * 获得dom控件的id
 * @param name  name可以为英文名称或者以field开头的id，最终返回的是以field开头的id  明细表如果存在重名字段会返回第一个明细表的此字段id  默认遍历20个可能存在的明细表 可以设置count值增加遍历深度
 * @param prefix  需要field字符串前缀，默认为true
 * @param detailNumber 明细表号码  用来重名字段区分
 * @param count   查询字段所在明细表循环次数默认20次
 * @returns {*}
 */
function getFieldId(name,prefix,detailNumber,count){
    if (validatenull(detailNumber)){
        if (validatenull(prefix)||!(typeof prefix==="boolean")){
            prefix = true;
        }
        if (!contains(name,"field")){
            let temp =  WfForm.convertFieldNameToId(name,'main',prefix);
            if (isBlank(temp)){
                for(var i=1;i<=($.isNumeric(count)?parseInt(count):20);i++){
                    temp = WfForm.convertFieldNameToId(name,"detail_"+i,prefix);
                    if (isNotBlank(temp)){
                        name = temp;
                        break;
                    }
                }
                if (isBlank(temp)){
                    WfForm.showMessage("未能查询到"+name+"所在字段", 2, 10);
                    return;
                }
                return temp;
            }else{
                return temp;
            }
        }else{
            return name;
        }
    }else{
        if (validatenull(prefix)||!(typeof prefix==="boolean")){
            prefix = true;
        }
        if (!contains(name,"field")){
            let temp =   WfForm.convertFieldNameToId(name,"detail_"+detailNumber,prefix);
            if (isBlank(temp)){
                    WfForm.showMessage("在明细表"+detailNumber+"未能查询到"+name+"所在字段", 2, 10);
                    return;
            }else{
                return temp;
            }
        }
    }
}

/**
 * 获得控件的id 及详细信息
 * @param name 字段名称
 * @param detailNumber 指定的明细表号
 * @returns {{detailNumber: number, id: *, isDetail: boolean}|{detailNumber: number, id, isDetail: boolean}|{id, isDetail: boolean}|{id: *, isDetail: boolean}}
 */
function getFieldIdAndDetail(name,detailNumber,count){
    if (validatenull(detailNumber)){
        if (!contains(name,"field")){
            let temp =  WfForm.convertFieldNameToId(name);
            if (isBlank(temp)){
                let detailNumber = 1;
                for(var i=1;i<=($.isNumeric(count)?parseInt(count):20);i++){
                    temp = WfForm.convertFieldNameToId(name,"detail_"+i);
                    if (isNotBlank(temp)){
                        name = temp;
                        detailNumber = i;
                        break;
                    }
                }
                if (isBlank(temp)){
                    WfForm.showMessage("未能查询到"+name+"所在字段", 2, 10);
                    return;
                }
                return {id:temp,isDetail:true,detailNumber:detailNumber};
            }else{
                return {id:temp,isDetail:false};
            }
        }else{
            const info = WfForm.getFieldInfo(name.replace("field",""));
            if (info.isDetail){
                return {id:name,isDetail: true,detailNumber:parseInt(info.tableMark.replace("detail_",""))};
            }else{
                return {id:name,isDetail:false}
            }
        }
    }else {
        if (!contains(name,"field")){
            let temp =  WfForm.convertFieldNameToId(name,"detail_"+parseInt(detailNumber));
            if (isNotBlank(temp)){
                return {id:temp,isDetail:true,detailNumber:detailNumber};
            }else{
                    WfForm.showMessage("在明细表"+detailNumber+"未能查询到"+name+"所在字段", 2, 10);
                    return;
            }
        }else{
            const info = WfForm.getFieldInfo(name.replace("field",""));
            if (info.isDetail){
                return {id:name,isDetail: true,detailNumber:parseInt(info.tableMark.replace("detail_",""))};
            }else{
                return {id:name,isDetail:false}
            }
        }
    }
}

/**
 * 获取字段的值
 * @param name
 * @param rowIndex
 * @param detailNumber
 * @returns {*}
 */
function getFieldValue(name,rowIndex,detailNumber){
    var json = getFieldIdAndDetail(name,detailNumber);
    if (json.isDetail){
        if (!validatenull(rowIndex)&&$.isNumeric(rowIndex)){
            return WfForm.getFieldValue(json.id+"_"+rowIndex);
        }else{
            var rows = getRowIndexStr(json.detailNumber);
            if (rows.length==0){
                msgBox("明细表"+json.detailNumber+"没有数据！")
                return ;
            }
            return WfForm.getFieldValue(json.id+"_"+rows[0]);
        }
    }else{
        return WfForm.getFieldValue(json.id);
    }
}

/**
 * 获取明细行主键值  可以指定明细行号
 * @param detailNumber
 * @param rowIndex
 * @returns {*|*[]}
 */
function getDetailRowKey(detailNumber,rowIndex){
        var d = parseInt(detailNumber);
        var rows = getRowIndexStr(d);
        const tds = $($('#oTable'+(d-1)).find("tr.detail_data_row")[0]).find("td");
        let field;
        for(var i=0;i<tds.length;i++){
            var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
            if (!validatenull(fieldname)){
                field =  fieldname;
                break;
            }
        }
        if (!validatenull(rowIndex)){
            return WfForm.getDetailRowKey(getFieldId(field,true,detailNumber)+"_"+rowIndex);
        }else{
            var arr = [];
            for(var i=0;i<rows.length;i++){
                arr.push(WfForm.getDetailRowKey(getFieldId(field,true,detailNumber)+"_"+rows[i]))
            }
            return arr;
        }
}

/**
 * 获取浏览框的显示值
 * @param name
 */
function getBrowserShowNameOA(name,rowIndex){
    var id = getFieldId(name);
    if (!validatenull(rowIndex)){
        id = id+"_"+rowIndex;
    }
    return WfForm.getBrowserShowName(id);
}


/**
 * 获取各种类型字段的显示值  文本/浏览框/选择框/附件/日期
 * @param name  字段名称
 * @param rowIndex  明细行标识
 * @param detailNumber  明细表号码，当字段名称相同时，用来区分是明细表的字段还是主表字段
 * @returns {string}
 */
function getShowNameOA(name,rowIndex,detailNumber){
    var id = getFieldId(name,true,detailNumber);
    var tempid = id.replace("field","");
    var fieldInfo = WfForm.getFieldInfo(tempid);
    if (fieldInfo.hasOwnProperty("browserattr")){//针对日期时间类型进行判断   如果为日期类型取实际值  因为日期类型浏览框取显示值为空
        if (!validatenull(rowIndex)){
            id = id+"_"+rowIndex;
        }
        if (fieldInfo.isDetail){
            //  日期时间格式  fielddbtype:"varchar(100)"
            //  时间格式  char(5)
            // 日期格式  fielddbtype:"char(10)"
           if (["varchar(100)","char(5)","char(10)"].indexOf(fieldInfo.fielddbtype)>-1){
               return WfForm.getFieldValue(id);
           }else{
               return WfForm.getBrowserShowName(id);
           }
        }else{
            return WfForm.getBrowserShowName(id);//明细表的时间类型数据不能正常显示   主表的可以正常显示
        }
    }else if (fieldInfo.hasOwnProperty("selectattr")){
        if (!validatenull(rowIndex)){
            id = id+"_"+rowIndex;
        }
        return WfForm.getSelectShowName(id);
    }else if (fieldInfo.hasOwnProperty("fileattr")){
        if (!validatenull(rowIndex)){
            id = id+"_"+rowIndex;
        }
        var arr = [];
        var as = $("div[data-fieldmark='"+id+"']").find('a');
        for(var i=0;i<as.length;i++){
            arr.push( $(as[i]).text());
        }
        return arr;
    }else{
        if (!validatenull(rowIndex)){
            id = id+"_"+rowIndex;
        }
        return WfForm.getFieldValue(id)
    }
}


/**
 * 设置字段的值
 * @param name
 * @returns {*}
function setFieldValueOA(name,value){
    var json = getFieldIdAndDetail(name);//如果是明细行则会批量设置
    if (json.isDetail){
        var rows = WfForm.getDetailAllRowIndexStr("detail_"+json.detailNumber);
        if (rows!=null&&rows.length>0){
            rows = rows.split(",");
            rows.forEach(i=>{
                WfForm.changeFieldValue(json.id+"_"+i, {value:value});
            })
        }
    }else {
        setTimeout(function(){
            WfForm.changeFieldValue(json.id, {value:value});
        },300)
    }
}*/

/**
 * 设置字段的值（全能版） 主表明细表均可设置,如果不设置rowIndex明细行会进行遍历设置,文本 浏览框 选择框均可设置
 * @param name id或者名称
 * @param value 文本、选择框、check框：值； 浏览框： id|name,id|name,...  如 5666|张三,5667|李四  如果想设置浏览框为空则可将value设为null或""
 * @param rowIndex  明细行标识 如果传入则只更改此行数值
 * @param detailNumber 明细表号码  可不填  防止字段名冲突使用  也可以将name赋值为id（如 field123）解决字段名冲突的问题
 */
function setFieldValueOA(name,value,rowIndex,detailNumber){
    const id = getFieldId(name,true,detailNumber);
    if (validatenull(id)){
        msgError("未查询到"+name+"所在字段！");
        return;
    }
    const pureNumber = id.replace("field", "");
    const attrInfo = WfForm.getFieldInfo(pureNumber);
    if (attrInfo.isDetail){
        if (validatenull(rowIndex)||!$.isNumeric(rowIndex)||parseInt(rowIndex)<0){
            let rows = WfForm.getDetailAllRowIndexStr(attrInfo.tableMark);
            if (rows!=null&&rows.length>0){
                rows = rows.split(",");
                rows.forEach(i=>{
                    if (attrInfo.hasOwnProperty("browserattr")){//浏览按钮
                        let p1 = "";
                        let p2 = [];
                        if(!validatenull(value)){
                            var arr1 = value.split(",");
                            var ids = [];
                            var objs = [];
                            for(var j=0;j<arr1.length;j++){
                                ids.push(arr1[j].split("|")[0]);
                                var obj = {};
                                obj.id = arr1[j].split("|")[0]
                                if (validatenull(arr1[j].split("|")[1])){
                                    obj.name = arr1[j].split("|")[0]
                                }else {
                                    obj.name = arr1[j].split("|")[1]
                                }
                                objs.push(obj);
                            }
                            p1 = ids.join(",");
                            p2 = objs;
                        }
                        setTimeout(function (){
                            //修改浏览框字段的值，必须有specialobj数组结构对象
                            WfForm.changeFieldValue(id+"_"+i, {
                                value: p1,
                                specialobj:p2
                            });
                        },200);
                    }else{//文本 check框
                        setTimeout(function (){
                            WfForm.changeFieldValue(id+"_"+i, {value:value});
                        },200);
                    }
                })
            }
        }else{//传了rowIndex
            if (attrInfo.hasOwnProperty("browserattr")){//浏览按钮
                let p1 = "";
                let p2 = [];
                if(!validatenull(value)){
                    var arr1 = value.split(",");
                    var ids = [];
                    var objs = [];
                    for(var j=0;j<arr1.length;j++){
                        ids.push(arr1[j].split("|")[0]);
                        var obj = {};
                        obj.id = arr1[j].split("|")[0]
                        if (validatenull(arr1[j].split("|")[1])){
                            obj.name = arr1[j].split("|")[0]
                        }else {
                            obj.name = arr1[j].split("|")[1]
                        }
                        objs.push(obj);
                    }
                    p1 = ids.join(",");
                    p2 = objs;
                }
                setTimeout(function (){
                    //修改浏览框字段的值，必须有specialobj数组结构对象
                    WfForm.changeFieldValue(id+"_"+rowIndex, {
                        value: p1,
                        specialobj:p2
                    });
                },100);
            }else{//文本 check框
                setTimeout(function (){
                    WfForm.changeFieldValue(id+"_"+rowIndex, {value:value});
                },100);
            }
        }
    }else {
        if (attrInfo.hasOwnProperty("browserattr")){//浏览按钮
            var p1 = "";
            var p2 = [];
            if(!validatenull(value)){
                var arr1 = value.split(",");
                var ids = [];
                var objs = [];
                for(var i=0;i<arr1.length;i++){
                    ids.push(arr1[i].split("|")[0]);
                    var obj = {};
                    obj.id = arr1[i].split("|")[0];
                    if (validatenull(arr1[i].split("|")[1])){
                        obj.name = arr1[i].split("|")[0]
                    }else {
                        obj.name = arr1[i].split("|")[1]
                    }
                    objs.push(obj);
                }
                p1 = ids.join(",");
                p2 = objs;
            }
            setTimeout(function (){
                //修改浏览框字段的值，必须有specialobj数组结构对象
                WfForm.changeFieldValue(id, {
                    value: p1,
                    specialobj:p2
                });
            },100);
        }else{//文本
            setTimeout(function(){
                WfForm.changeFieldValue(id, {value:value});
            },100);
        }
    }
}

/**
 * 控制选择框只显示options的选项
 * @param name
 * @param options
 */
function setSelectOption(name,options){
    const json = getFieldIdAndDetail(name);
    if (json.isDetail){
        var rows = getRowIndexStr(json.detailNumber);
        for(var i=0;i<rows.length;i++){
            WfForm.controlSelectOption(json.id+"_"+rows[i], options);  //控制选择框只显示options的选项
        }
    }else {
        WfForm.controlSelectOption(json.id, options);  //控制选择框只显示options的选项
    }
}


function setFieldAttrWhenKnowId(id,mode){
    WfForm.changeFieldAttr(id, mode);  //字段属性修改模式
    if (mode==4){//仅隐藏本字段时需要做额外界面处理
        $("#"+id).parents("td").first().attr("style","border:0");
        $("div[data-fieldmark='"+id+"']").parent().prev().hide();
        $("#"+id).parents("td").first().prev().attr("style","background-color: #fff!important;border:0!important;")
    }else if (mode==6){
        WfForm.changeFieldAttr(id, 3);  //字段属性修改模式
        setTimeout(function (){
            $("#"+id).attr("readonly",true);
        },300)
    }else {
        var readonly = $("#"+id).attr("readonly");
        if (readonly){
            setTimeout(function (){
                $("#"+id).removeAttr("readonly");
            },300)
        }
        $("div[data-fieldmark='"+id+"']").parent().prev().show();
        $("#"+id).parents("td").first().removeAttr("style");
        $("#"+id).parents("td").first().prev().removeAttr("style")
    }
}
/**
 * 添加placeholder  目前只能用于主表文本类型输入设置placeholder
 * @param name  name为名称，如wlbm或者id，如field12122
 * @param txt   txt为想要添加的placeholder内容
 */
function setPlaceholder(name,txt){
    const id = getFieldId(name);
    //为明细行字段添加placeholder时候，建议使用class配合明细行增删监听添加placeholder属性
    const type = $("#"+id).attr("type");
    if (type=="hidden"){
        var wf = $("#"+id).parent().find(".wf-input-main");
        $(wf[0]).attr("placeholder","  "+txt);
    }else{
        $("#"+id).attr("placeholder","  "+txt)
    }
}

/**
 * 设置字段的属性 name为字段名称wldm或field111，mode为模式整型 如下：
 * 1：只读，2：可编辑，3：必填，4：隐藏字段标签及内容，5:隐藏字段所在行(行内单元格不要存在行合并) 6:必填且只读（对浏览框无效）
 * 如果所选字段为明细行则隐藏的话该列
 * @param name
 * @param mode
 * @param rowIndex  行标识  如果此参数不为空那么只改变改行该字段的属性 4,5模式除外  4 5模式标识隐藏明细行该列
 * @param clazz   类选择器
 */
function setFieldAttr(name,mode,rowIndex,clazz,detailNumber){
    const json = getFieldIdAndDetail(name,detailNumber);
    const id = json.id;
    if(json.isDetail){
        if (validatenull(rowIndex)){
            var rows = getRowIndexStr(json.detailNumber);
            for(var i=0;i<rows.length;i++){
                WfForm.changeFieldAttr(id+"_"+rows[i], mode==4||mode==5?2:mode);  //字段属性修改模式
                if (mode==4||mode==5){
                    WfForm.changeFieldValue(id+"_"+rows[i], {value:null});
                }
            }
            if(mode==4||mode==5){
                if(!validatenull(clazz)){
                    $('.'+clazz).hide()
                }
            }else{
                if(!validatenull(clazz)){
                    $('.'+clazz).show();
                }
            }
        }else{
            WfForm.changeFieldAttr(id+"_"+rowIndex, mode);  //字段属性修改模式
            if(mode==4||mode==5){
                if(!validatenull(clazz)){
                    WfForm.changeFieldValue(id+"_"+rowIndex, {value:null});
                    $('.'+clazz).hide()
                }
            }else{
                if(!validatenull(clazz)){
                    $('.'+clazz).show();
                }
            }
        }
    }else{
        WfForm.changeFieldAttr(id, mode);  //字段属性修改模式
        if (mode==4){//仅隐藏本字段时需要做额外界面处理
            $("#"+id).parents("td").first().attr("style","border:0");
            $("div[data-fieldmark='"+id+"']").parent().prev().hide();
            $("#"+id).parents("td").first().prev().attr("style","background-color: #fff!important;border:0!important;")
            WfForm.changeFieldValue(id, {value:null});
        }else if (mode==6){
            WfForm.changeFieldAttr(id, 3);  //字段属性修改模式
            setTimeout(function (){
                $("#"+id).attr("readonly",true);
            },300)
        }else {
            var readonly = $("#"+id).attr("readonly");
            if (readonly){
                setTimeout(function (){
                    $("#"+id).removeAttr("readonly");
                },300)
            }
            $("div[data-fieldmark='"+id+"']").parent().prev().show();
            $("#"+id).parents("td").first().removeAttr("style");
            $("#"+id).parents("td").first().prev().removeAttr("style")
            if (mode==5){
                WfForm.changeFieldValue(id, {value:null});
            }
        }
    }
}


/**
 * 更改字段的中文Label值
 * @param name 字段名
 * @param label label内容
 * @param detailNumber  明细表号码  明细表列名修改请用setDetailTitle()
 * @param td  第几列包含checkbox列和序号列  明细表列名修改请用setDetailTitle()
 */
function setFieldLabel(name,label,detailNumber,td){
    if (td==0){
        msgError("td必须为大于0的数字")
        return;
    }
    var json = getFieldIdAndDetail(name,detailNumber);
    if (json.isDetail){
        var detailCellMark ="detail_"+json.detailNumber+"_1_"+(parseInt(td)-1);
        var div = $("div[data-cellmark='"+detailCellMark+"']");
        div.find("span").text(label)
    }else{
        $($('div[data-fieldname='+name+']').parent().prev().find('span')).text(label);
    }
}
/*
var jsonArr = [
    {
        bgdh_:"",gc:"",cpbmxh:"",fjbm:"",zjlh:"",yzjlh:"",qty:"",xzjlh:"",sl:""
    }
]
*/
/**
 * 添加明细行并设置初始值
 * @param detailNumber
 * @param jsonArr  key加_可表示此字段为浏览框类型  如果不加则无法映射浏览框类型字段
 */
function addDetailRow(detailNumber,jsonArr,callback){
    jsonArr.forEach(item=>{
        var keys = Object.keys(item);
        var addObj = {};
        for(var i=0;i<keys.length;i++){
            if (contains(keys[i],"_")){
                var key = keys[i].replace("_","");
                var field = WfForm.convertFieldNameToId(key, "detail_"+detailNumber);
                var content = item[keys[i]];
                if (contains(content,"undefined")||validatenull(content)){
                    content = "";
                }
                if (validatenull(content)){
                    //msgBox("第"+(i+1)+"个key对应值为空")
                    console.log("第"+(i+1)+"个key对应值为空")
                    //continue;
                }
                var value = [];
                var specialobj = [];
                var arr = content.split(",");
                for(var j=0;j<arr.length;j++){
                    if (contains(arr[j],"|")){
                        var idStr = arr[j].split("|")[0];
                        var nameStr = arr[j].split("|")[1];
                        value.push(idStr);
                        var itemObj = {};
                        itemObj.id = idStr;
                        itemObj.name = nameStr ;
                        specialobj.push(itemObj);
                    }else{
                        value.push(arr[j]);
                        var itemObj = {};
                        itemObj.id = arr[j];
                        itemObj.name = arr[j] ;
                        specialobj.push(itemObj);
                    }
                }
                addObj[field] = {value:value.join(","),specialobj:specialobj};
            }else{
                var field = WfForm.convertFieldNameToId(keys[i], "detail_"+detailNumber);
                var fieldVal = item[keys[i]];
                if (validatenull(fieldVal)){
                    fieldVal = "";
                }else if(contains(fieldVal,"undefined")){
                    fieldVal = "";
                }
                addObj[field] = {value:fieldVal};
            }
        }
        WfForm.addDetailRow("detail_"+detailNumber, addObj);
    });
    if (callback instanceof Function){
        callback();
    }
}

/*function addDetailRowOAAsync(detailNumber, jsonArr,callback) {
    return new Promise((resolve, reject) => {
        try {
                (async () => {
                        for (const item of jsonArr) {
                            var keys = Object.keys(item);
                            var addObj = {};
                            for(var i=0;i<keys.length;i++){
                                if (contains(keys[i],"_")){
                                    var key = keys[i].replace("_","");
                                    var field = WfForm.convertFieldNameToId(key, "detail_"+detailNumber);
                                    var content = item[keys[i]];
                                    if (contains(content,"undefined")||validatenull(content)){
                                        content = "";
                                    }
                                    if (validatenull(content)){
                                        //msgBox("第"+(i+1)+"个key对应值为空")
                                        console.log("第"+(i+1)+"个key对应值为空");
                                        //continue;
                                    }
                                    var value = [];
                                    var specialobj = [];
                                    /!*if (content instanceof Array&&content.length>0){
                                        content = content[0];
                                    }else if(validatenull(content)){
                                        content = "";
                                    }*!/
                                    var arr = content.split(",");
                                    for(var j=0;j<arr.length;j++){
                                        if (contains(arr[j],"|")){
                                            var idStr = arr[j].split("|")[0];
                                            var nameStr = arr[j].split("|")[1];
                                            value.push(idStr);
                                            var itemObj = {};
                                            itemObj.id = idStr;
                                            itemObj.name = nameStr ;
                                            specialobj.push(itemObj);
                                        }else{
                                            value.push(arr[j]);
                                            var itemObj = {};
                                            itemObj.id = arr[j];
                                            itemObj.name = arr[j] ;
                                            specialobj.push(itemObj);
                                        }
                                    }
                                    addObj[field] = {value:value.join(","),specialobj:specialobj};
                                }else{
                                    var field = WfForm.convertFieldNameToId(keys[i], "detail_"+detailNumber);
                                    var fieldVal = item[keys[i]];
                                    if (validatenull(fieldVal)){
                                        fieldVal = "";
                                    }else if(contains(fieldVal,"undefined")){
                                        fieldVal = "";
                                    }
                                    addObj[field] = {value:fieldVal};
                                }
                            }
                            //await new Promise(resolve => setTimeout(resolve, 0)); // 异步等待，给浏览器留出处理其他任务的时间  防止卡死

                            WfForm.addDetailRow("detail_" + detailNumber, addObj);
                        }
                        if (callback instanceof Function){
                            callback();
                        }
                        resolve();
                    })();
        } catch (error) {
            // 如果发生错误，调用reject并传入错误信息
            reject(error);
        }
    });
}*/
/**
 * 分块向明细表插入数据
 * @param detailNumber  明细表号码
 * @param jsonArr  明细表数组
 * @param callback  回调
 * @param chunkSize  分块大小
 * @returns {Promise<void>}
 */
async function addDetailRowOAAsync(detailNumber, jsonArr, callback, chunkSize = 50) {
    try {
        const chunks = chunkArray(jsonArr, chunkSize);

        for (const chunk of chunks) {
            await Promise.all(chunk.map(async item => {
                const addObj = {};
                for (const [key, content] of Object.entries(item)) {
                    if (key.includes("_")) {
                        const fieldName = WfForm.convertFieldNameToId(key.replace("_", ""), "detail_" + detailNumber);
                        let value = [];
                        let specialobj = [];

                        if (typeof content === 'string') {
                            const arr = content.split(",");
                            for (const str of arr) {
                                const [idStr, nameStr = idStr] = str.split("|") || [str, str];
                                value.push(idStr);
                                specialobj.push({ id: idStr, name: nameStr });
                            }
                        }

                        addObj[fieldName] = { value: value.join(","), specialobj };
                    } else {
                        const fieldName = WfForm.convertFieldNameToId(key, "detail_" + detailNumber);
                        if (content==0){
                            addObj[fieldName] = { value: content};
                        }else{
                            addObj[fieldName] = { value: (content || "").toString().replace("undefined", "").trim() };
                        }
                    }
                }
               // console.log(addObj)
                WfForm.addDetailRow("detail_" + detailNumber, addObj);
            }));

            // 引入延时，给浏览器留出处理其他任务的时间
            await new Promise(resolve => setTimeout(resolve, 0));
        }

        if (typeof callback === 'function') {
            callback();
        }
    } catch (error) {
        // 如果发生错误，抛出异常
        console.error(error)
        throw error;
    }
}

function chunkArray(arr, size) {
    const chunks = [];
    for (let i = 0; i < arr.length; i += size) {
        chunks.push(arr.slice(i, i + size));
    }
    return chunks;
}
/**
 * 添加明细行并设置初始值
 * @param detailNumber
 * @param jsonArr  key加_可表示此字段为浏览框类型  如果不加则无法映射浏览框类型字段
 */
function addDetailRowOA(detailNumber,jsonArr,callback){
    jsonArr.forEach(item=>{
        var keys = Object.keys(item);
        var addObj = {};
        for(var i=0;i<keys.length;i++){
            if (contains(keys[i],"_")){
                var key = keys[i].replace("_","");
                var field = WfForm.convertFieldNameToId(key, "detail_"+detailNumber);
                var content = item[keys[i]];
                if (contains(content,"undefined")||validatenull(content)){
                    content = "";
                }
                if (validatenull(content)){
                    //msgBox("第"+(i+1)+"个key对应值为空")
                    console.log("第"+(i+1)+"个key对应值为空");
                    //continue;
                }
                var value = [];
                var specialobj = [];
                var arr = content.split(",");
                for(var j=0;j<arr.length;j++){
                    if (contains(arr[j],"|")){
                        var idStr = arr[j].split("|")[0];
                        var nameStr = arr[j].split("|")[1];
                        value.push(idStr);
                        var itemObj = {};
                        itemObj.id = idStr;
                        itemObj.name = nameStr ;
                        specialobj.push(itemObj);
                    }else{
                        value.push(arr[j]);
                        var itemObj = {};
                        itemObj.id = arr[j];
                        itemObj.name = arr[j] ;
                        specialobj.push(itemObj);
                    }
                }
                addObj[field] = {value:value.join(","),specialobj:specialobj};
            }else{
                var field = WfForm.convertFieldNameToId(keys[i], "detail_"+detailNumber);
                var fieldVal = item[keys[i]];
                if (validatenull(fieldVal)){
                    fieldVal = "";
                }else if(contains(fieldVal,"undefined")){
                    fieldVal = "";
                }
                addObj[field] = {value:fieldVal};
            }
        }
        WfForm.addDetailRow("detail_"+detailNumber, addObj);
    });
    if (callback instanceof Function){
        callback();
    }
}

/**
 * 根据明细行id（主键）更新明细行数据 （DOM）
 * @param rowData
 */
function updateDetailRowByIdOA(detailNumber,rowData,rows){
    loop1:for(var i=0;i<rows.length;i++){
        loop2:for(var j=0;j<rowData.length;j++){
            if (getDetailRowKey(detailNumber,rows[i])===rowData[j].id){
                var keys = Object.keys(rowData[j]);
                loop3:for(var k=0;k<keys.length;k++){
                    if (keys[k]==="id"||keys[k]==="mainid"){
                        continue loop3
                    }
                    var val = getFieldValue(keys[k],rows[i])
                    if(val!=rowData[j][keys[k]]){
                        setFieldValueOA( keys[k],rowData[j][keys[k]],rows[i]);
                    }
                }
                continue loop1;
            }
        }
    }
}

/**
 * 按照指定条件删除指定明细表的明细行
 * @param detailNumber
 * @param condition
 */
function delDeatilRowOA(detailNumber,condition){
    var detail = "detail_"+detailNumber;
    if (!validatenull(condition)){
        if (condition=="all"){
            WfForm.delDetailRow(detail, "all");
        }else{
            WfForm.delDetailRow(detail, condition);
        }
    }else{
        WfForm.delDetailRow(detail, "all");
    }
}

/*var condition = {
   wlbm:"1",   //0:为空  1:非空  2:是数字 3:为指定值后面拼接|val如 3|是 4:包含指定值拼接*val 如4*30  31:主控制字段的值处于所提供数组内拼接|v1,v2,v3 如 31|1001,1002,1003
   wlms:"2",
    bb:"3|A",
    desc:"4*工具研究部",
    scgcnew:"31|1001,1002,1003"
}*/
//var condition = "1,2,3"; 1,2,3行锁定
//var condition = "1-5"; 1-5行锁定
//var condition = "-3"  前三行锁定
//var condition = "-5"  后五行锁定
//0:为空  1:非空  2:是数字 3:为指定值后面拼接|val如 3|是 4:包含指定值拼接*val 如4*30  31:主控制字段处于所提供数组内拼接|v1,v2,v3 如 31|1001,1002,1003
/**
 *
 * @param detailNumber  明细表号码
 * @param condition  condition有多种模式可选如上  不填默认锁定全表
 * @param msg  额外的提示信息
 */
function frozeDetailRowOA(detailNumber,condition,msg){
    WfForm.registerCheckEvent(WfForm.OPER_DELROW+detailNumber, function(callback){
        let detail = "detail_"+detailNumber;
        let ifCanDel = true;
        if (validatenull(msg)){
            msg = "";
        }
        if (validatenull(condition)){
            msgError("明细表"+detailNumber+"禁止删除"+msg,2);
            return;
        }
        let rowsStr = WfForm.getDetailCheckedRowIndexStr(detail);//获取选中的明细行下标
        let endMsg = "";
        if (validatenull(rowsStr)){
            msgWarn("请先选择想要删除的明细行",2);
            return;
        }
        let rows = rowsStr.split(",");
        let cantDelArr = [];//不可删除的行序号

        let type = getParaTypeOA(condition);
        if (type == "string"){//字符串
            if (contains(condition,",")){//“,”分隔形式的入参
                var tempArr = condition.split(",");
                tempArr.forEach(i=>{
                    if (contains(rows,getRowIndexByXh(i))){
                        cantDelArr.push(i);
                        ifCanDel = false;
                    }
                });
                endMsg = "明细表"+detailNumber+"第 "+cantDelArr.join(",")+" 行禁止删除!"+msg;
            }else if (contains(condition,"-")){// 根据数据范围快速生成数组
                let tempArr = condition.split("-");
                let start = tempArr[0];
                let end = tempArr[1];
                if (!validatenull(start)&&!validatenull(end)){ //3-5
                    if (start>end&&(contains(rows,getRowIndexByXh(start))||contains(rows,getRowIndexByXh(end)))){
                        ifCanDel = false;
                        endMsg = "明细表"+detailNumber+"第 "+start+"或"+end+" 行禁止删除!"+msg;
                    }else if (start==end&&(contains(rows,getRowIndexByXh(start)))){
                        ifCanDel = false;
                        endMsg = "明细表"+detailNumber+"第 "+end+" 行禁止删除!"+msg;
                    }else {
                        for(let k=start;k<=end;k++){
                            if (contains(rows,getRowIndexByXh(k))){
                                ifCanDel = false;
                                endMsg = "明细表"+detailNumber+"第 "+condition+" 行禁止删除!"+msg;
                                break;
                            }
                        }
                    }
                }else if(validatenull(start)&&!validatenull(end)){//-5
                    var allRows = getRowIndexStr(detailNumber);
                    if (allRows.length<=parseInt(end)){
                        ifCanDel = false;
                        endMsg = "明细表"+detailNumber+"倒数后 "+end+" 行禁止删除!"+msg;
                    }else{
                        allRows.splice(allRows.length-end,end).forEach(i=>{
                            if (contains(rows,i)){
                                ifCanDel = false;
                                endMsg = "明细表"+detailNumber+"倒数后 "+end+" 行禁止删除!"+msg;
                            }
                        })
                    }
                }else if(!validatenull(start)&&validatenull(end)){//3-
                    var allRows = getRowIndexStr(detailNumber);
                    if (allRows.length<=parseInt(start)){
                        ifCanDel = false;
                        var tempRows = [];
                        rows.forEach(item=>{
                            tempRows.push(WfForm.getDetailRowSerailNum("detail_"+detailNumber, parseInt(item)));
                        })
                        endMsg = "明细表"+detailNumber+"第 "+tempRows.join(",")+" 行禁止删除!"+msg;
                    }else{
                        allRows.splice(0,start).forEach(i=>{
                            if (contains(rows,i)){
                                ifCanDel = false;
                                endMsg = "明细表"+detailNumber+"前 "+start+" 行禁止删除!"+msg;
                            }
                        })
                    }
                }else{
                    ifCanDel = false;
                    endMsg = "明细表"+detailNumber+"禁止删除"+msg;
                }
            }else{
                if ($.isNumeric(condition)){
                    if (contains(rows,getRowIndexByXh(condition))){
                        cantDelArr.push(condition);
                        ifCanDel = false;
                        endMsg = "明细表"+detailNumber+"第 "+cantDelArr.join(",")+" 行禁止删除!"+msg;
                    }
                }else{
                    ifCanDel = false;
                    endMsg = "明细表"+detailNumber+"禁止删除"+msg;
                }
            }
        }else if (type == "object"){//json obj
            var keys = Object.keys(condition);
            var checkFunc = function (keyVal,val,keyName){
                var ret = {
                    res:true,
                    msg:""
                }
                if (contains(keyVal,"|")){
                    var p1 = keyVal.split("|")[0];//mode
                    var p2 = keyVal.split("|")[1];//formatSTR
                    if (p1=="3"){
                        ret.res = !(p2==val);
                        ret.msg = keyName+"等于'"+val+"'禁止删除";
                    }else if (p1=="31"){
                        ret.res = !contains(p2,val);
                        ret.msg = keyName+"包含'"+val+"'禁止删除!";
                    }
                }else if (contains(keyVal,"*")){
                    var p1 = keyVal.split("*")[0];//mode
                    var p2 = keyVal.split("*")[1];//formatSTR
                    if (p1=="4"){
                        ret.res = !contains(val,p2);
                        ret.msg = keyName+"包含'"+p2+"'禁止删除!";
                    }
                }else if ($.isNumeric(keyVal)){//是数字
                    if (keyVal=="0"){
                        ret.res = isNotBlank(val);
                        ret.msg = keyName+"为空禁止删除!"
                    }else if (keyVal=="1"){
                        ret.res = isBlank(val);
                        ret.msg = keyName+"非空禁止删除!"
                    }else if (keyVal=="2"){
                        ret.res = $.isNumeric(val);
                        ret.msg = keyName+"为数字禁止删除!"
                    }
                }
                return ret;
            }
            rows.forEach(row=>{
                keys.forEach(key=>{//键
                    var tempVal = getFieldValue(getFieldId(key)+"_"+row);//值
                    var keyName = WfForm.getFieldInfo(getFieldId(key).replace("field","")).fieldlabel;//获得中文名
                    var check = checkFunc(condition[key],tempVal,keyName);
                    if (!check.res){
                        //msgBox(check.msg);
                        ifCanDel = false;
                        endMsg = check.msg
                        return;
                    }
                })
            })
        }else if (type == null){//condition为空默认整个明细行不能删除
            ifCanDel = false;
            endMsg = "明细表"+detailNumber+"禁止删除"+msg;
        }
        if (!ifCanDel){
            msgError(endMsg,2);
            return;
        }else{
            callback();    //继续提交需调用callback，不调用代表阻断
        }
    });
}

/**
 * 控制明细表显隐和相关属性
 * @param detailNumber  明细表号码
 * @param detailShow   明细表是否显示  true 显示  false 隐藏
 * @param isSaveData  是否保留数据
 */
function controlDetailPropertity(detailNumber,detailShow,isSaveData){
    if (detailShow){
        $('#oTable'+(detailNumber-1)).parent().parent().parent().parent().parent().parent().parent().show();
        if (isSaveData){
            var jsonStr = sessionStorage.getItem(LOCALSTORAGE_KEY_controlDetailPropertity+"_"+detailNumber);
            if(!validatenull(jsonStr)){
                var jsonArr = JSON.parse(jsonStr);
                addDetailRowOA(detailNumber,jsonArr);
            }
        }
    }else{
        var jsonArr = getRowsDataExtraOA(detailNumber);
        $('#oTable'+(detailNumber-1)).parent().parent().parent().parent().parent().parent().parent().hide();
        if (!validatenull(jsonArr)&&isSaveData){
            sessionStorage.setItem(LOCALSTORAGE_KEY_controlDetailPropertity+"_"+detailNumber,JSON.stringify(jsonArr));
        }
        delDeatilRowOA(detailNumber);
    }
}

/**
 * 控制明细行check框禁用勾选
 * @param detailNumber  明细表号
 * @param condition  需要禁用的行标示，禁用全部行:all,禁用部分行：”1,2,3”
 */
function disableDetailRowsCheck(detailNumber,condition){
    WfForm.controlDetailRowDisableCheck("detail_"+detailNumber, condition, true);
}

/**
 * 控制明细行check框可以勾选
 * @param detailNumber  明细表号
 * @param condition   需要选中的行标示，选中全部行:all,选中部分行：”1,2,3”
 */
function enableDetailRowsCheck(detailNumber,condition){
    WfForm.controlDetailRowDisableCheck("detail_"+detailNumber, condition, false);
}

/**
 * 控制明细行行的显隐
 * @param detailNumber 明细表号
 * @param rows  行标示 如"3,5"为第三行和第五行
 * @param showOrHide  true：展示  false:隐藏
 */
function detailRowDisplayOA(detailNumber,xhRows,showOrHide){
    var indexArr = [];
    xhRows.split(",").forEach(xh=>{
        indexArr.push(getRowIndexByXh(xh,detailNumber));
    })
    WfForm.controlDetailRowDisplay("detail_"+detailNumber,indexArr.join(","), !showOrHide);
}


/**
 * 设置某行或者多行明细行数据只读
 * @param detailNumber  明细表号
 * @param indexArr  行下标字符串 如0,2,3为行下标为0,2,3的
 */
function detailRowReadonlyOA(detailNumber,indexArr){
    if (validatenull(indexArr)){
        indexArr = getRowIndexStr(detailNumber);
    }else{
        indexArr = indexArr.split(",");
    }
    var tds = $($('#oTable'+(detailNumber-1)).find("tr[data-rowindex='"+indexArr[0]+"']")[0]).find("td");
    indexArr.forEach(item=>{
        for(var i=0;i<tds.length;i++){
            var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
            if (!validatenull(fieldname)){
                WfForm.changeFieldAttr(getFieldId(fieldname,true,detailNumber)+"_"+item, 1);  //字段修改为只读
            }
        }
    })
}

/**
 *  为字段绑定改变监听事件  name可以用","隔开传多个 主表明细表均可 但不能混用
 * @param name
 * @param callback
 */
function setFieldListener(name,callback,detailNumber){
    if (!validatenull(name)&&contains(name,",")){
        var arr = name.split(",");
        var isDetail = false;
        for(var i=0;i<arr.length;i++){
            var json = getFieldIdAndDetail(arr[i],detailNumber)
            isDetail = json.isDetail;
            arr[i] = json.id
        }
        if (isDetail){
            WfForm.bindDetailFieldChangeEvent(arr.join(","),function(id,rowIndex,value){
                callback(id,rowIndex,value)
            });
        }else{
            WfForm.bindFieldChangeEvent(arr.join(","), function(obj,id,value){
                callback(obj,id,value)
            });
        }

    }else{
        var json = getFieldIdAndDetail(name,detailNumber)
        if (json.isDetail){
            WfForm.bindDetailFieldChangeEvent(json.id,function(id,rowIndex,value){
                callback(id,rowIndex,value)
            });
        }else{
            WfForm.bindFieldChangeEvent(json.id, function(obj,id,value){
                callback(obj,id,value)
            });
        }
    }
}

/**
 *
 * @param type   action类型,可传多个,用","隔开,save:保存, submit:提交, 需另传明细表数, reject:退回 , add：添加行，需拼接明细表数，如add_1, del:删除行,需拼接明细表数，如del_1,vbefore:校验必填前触发事件,cbefore:页面关闭
 * @param func  func需调用callback  不调用代表阻断  func入参为callback
 */
function setActionListener(types,func){
    var json = {
        save:WfForm.OPER_SAVE,
        submit:WfForm.OPER_SUBMIT,
        reject:WfForm.OPER_REJECT,
        add:WfForm.OPER_ADDROW,
        del:WfForm.OPER_DELROW,
        vbefore:WfForm.OPER_BEFOREVERIFY,
        cbefore:WfForm.OPER_CLOSE
    }
    var arr = types.split(",");
    for(var i=0;i<arr.length;i++){
        var item = arr[i];
        if (contains(item,"_")){
            var t = item.split("_")[0]
            var d = item.split("_")[1]
            if(!validatenull(json[t])){
                arr[i] = json[t]+d
            }
        }else{
            if(!validatenull(json[arr[i]])){
                arr[i] = json[arr[i]]
            }
        }
    }
    WfForm.registerCheckEvent(arr.join(","), function(callback){
        func(callback);
        //callback();    //继续提交需调用callback，不调用代表阻断
    });
}

/**
 * 隐藏类选择器为class的列
 * @param clazz
 */
function hideClass(clazz){
   $("."+clazz).hide();
}

/**
 * 弹出信息框
 * @param msg  想要提示的信息内容
 * @param v1  1 警告 2 错误
 * @param v2  显示的时间  单位 秒
 */
function msgBox(msg,v1,v2){
    if (validatenull(v1)){
        v1 = 2;
    }
    if (validatenull(v2)){
        v2 = 10;
    }
    domArrange();
    WfForm.showMessage(msg, v1, v2);
}

/**
 * 控制台打印日志
 * @param msg
 */
function msgLog(msg){
    console.log(msg);
}

/**
 * 成功提示
 * @param msg  想要提示的信息内容
 * @param showtime  不填默认三秒
 */
function msgSuccess(msg,showtime){
    if (validatenull(showtime)){
        showtime = 2;//默认三秒
    }
    msgBox(msg,3,showtime);
}

/**
 * 警告提示
 * @param msg  想要提示的信息内容
 * @param showtime  不填默认三秒
 */
function msgWarn(msg,showtime){
    if (validatenull(showtime)){
        showtime = 3;//默认三秒
    }
    msgBox(msg,1,showtime)
}

/**
 * 错误提示
 * @param msg 想要提示的信息内容
 * @param showtime  不填默认三秒
 */
function msgError(msg,showtime){
    if (validatenull(showtime)){
        showtime = 3;
    }
    msgBox(msg,2,showtime)
}

/**
 * 全局loading提示
 * @param content
 * @param time
 */
function msgLoading(content,time){
    if (validatenull(time)){
        time = 3;
    }
    var length = $('.ant-message-notice-content').find('i').length;
    if (length==0){//如果当前没有已经弹出的提示那么就直接展示
        window.antd.message.loading(content, time)
    }else{
        //如果已经有了提示那么就进行处理
        domArrange();
        window.antd.message.loading(content, time)
    }
}

/**
 * 防止提示重叠自动下移
 */
function domArrange(){
    var pops = $('.ant-message-notice-content');
    for(let i=0;i<pops.length;i++){
        var marginTop = $(pops[i]).css("marginTop");
        var top = marginTop.replace("px","");
        marginTop = (parseInt(top)+40)+"px"
        $(pops[i]).css("marginTop",marginTop);
    }
}

/**
 * 全局提示摧毁
 */
function msgDestroy(){
    window.antd.message.destroy()
}

/*var json = [
    {
        name:"sl",mode:1
    },
    {
        name:"sl",mode:1
    }
]*/
/**
 * 批量处理字段属性
 * @param json
 */
function setFieldSSAttr(json){
    json.forEach(item=>{
        setFieldAttr(item.name,item.mode)
    })
}

/**
 * 在指定field位置添加链接路径
 * @param name  字段名称
 * @param link   链接地址
 * @param showName  显示名称
 * @param target  新建标签页或在本页打开默认新建标签页
 */
function createElementOA(name,link,showName,target='_blank'){
    WfForm.afterFieldComp(getFieldId(name),
        React.createElement("a",{
            href:link,
            target:target,
            children:showName,
            style:{"margin-left":"10px"},
            id:getFieldId(name)+"NEWATAG"
        }));
    $("#"+getFieldId(name)).hide();
    $("#"+getFieldId(name)+"span").hide();
}

/**
 * 根据当前登录人为明细行设置编辑权限
 * @param browserCol   指定依据的人力资源按钮所在列名
 * @param mode 模式值 0：其余隐藏 1:其余只读  默认其余隐藏   即只能看到登录人所在的一行
 * @param detailNumber  明细表号码  默认browserCol所在的第一个表
 * @param userid指定userid
 */
function setDetailAuth(browserCol,mode,detailNumber,userid){
    mode=validatenull(mode)?"0":mode;
  var baseInfo = WfForm.getBaseInfo();
  if (validatenull(userid)){
      userid = baseInfo.f_weaver_belongto_userid;//当前登录人id
  }
  var json = getFieldIdAndDetail(browserCol,detailNumber)
    if (!json.isDetail){
        msgBox("所选择的字段不是明细表的字段!");
        return null;
    }
    var rows;
    if (validatenull(detailNumber)||json.detailNumber!=detailNumber){
        rows = getRowIndexStr(json.detailNumber);
        detailNumber = json.detailNumber;
    }else{
        rows = getRowIndexStr(detailNumber);
    }
    var hideArr = [];
  rows.forEach(index=>{
      var rowUserid = WfForm.getFieldValue(json.id+"_"+index);
      if (rowUserid!=userid){
          hideArr.push(index);
      }
  });
  if ((mode==="0"||mode===0)&&hideArr.length>0){//隐藏
      detailRowReadonlyOA(detailNumber,hideArr.join(","))
      WfForm.controlDetailRowDisplay("detail_"+detailNumber, hideArr.join(","), true);
  }else if ((mode==="1"||mode==1)&&hideArr.length>0){//只读
      detailRowReadonlyOA(detailNumber,hideArr.join(","))
  }
}


/**
 * 根据序号获取行下标
 * @param xh
 */
function getRowIndexByXh(xh,detailNumber){
    if (!$.isNumeric(xh)){
        msgBox("传入序号必须为数字");
        return ;
    }
    if (xh<0){
        msgBox("传入序号必须大于等于1");
        return ;
    }
    if (validatenull(detailNumber)){
        detailNumber = 1;
    }
    var rows = getRowIndexStr(detailNumber);
    return rows[parseInt(xh)-1];
}

/**
 * 设置统计明细表detailNumber是否存在数据    存在数据col所在字段设置值为“1” 否则为“0”
 * @param detailNumber  明细表号码
 * @param col   预设的字段名
 */
function setDetailCountsFlag(detailNumber,setCol,time){
    if (validatenull(time)){
        time = 150;
    }else{
        time = parseInt(time);
    }
    var interval_setDetailCountsFlag_OA = setInterval(function (){
        var rows = getRowIndexStr(detailNumber);
        if (rows.length>0){
            setFieldValueOA(setCol,"1");
        }else{
            setFieldValueOA(setCol,"0");
        }
    },time);
}
/*var jsonArr = [
    {"col":"bghhsdj","exp":"<=","val":"10000"},
    {"col":"cezf","exp":">","val":"30"},
    {"col":"bghhsdj","exp":">","val":"10000","and":false},
    {"col":"cezf","exp":"!=","val":""},
    {"col":"cezf","exp":"!=","val":null},
]*/
/**
 * 根据所给条件校验明细行满足的条件  and字段表示是and关系还是or关系
 * @param detailNumber  明细表号码
 * @param jsonArr   条件数组  见上面示例
 * @param isall   是否需要每一行都满足条件  默认是  否则就只需要一行满足关系即可
 * @param rowIndexs   需要校验的明细行标识
 * @param setCol  需要设置的字段名   如果不需要可不填
 * @param isAlert 校验不通过时是否弹出提示
 * @param extraMsg 自定义弹出提示语
 * @returns {boolean}   返回校验结果  满足返回true 不满足返回false
 */
function checkDetailByCondition(detailNumber,jsonArr,isall,rowIndexs,setCol,isAlert,extraMsg){
    if(validatenull(jsonArr)){
        return;
    }
    if (validatenull(isall)){
        isall = true;
    }
    var nopassedline = [];
    for(let i=0;i<jsonArr.length;i++){
        var col = jsonArr[i].col;//目标字段
        var targetVal = jsonArr[i].val;//目标值
        var exp = jsonArr[i].exp;//目标表达式
        var and = jsonArr[i].and;
        if(validatenull(and)){
            jsonArr[i]["and"] = true;
        }
        var fun = function (a,b) {
            return a === b;
        };
        switch (exp) {
            case "=":
                fun = function (a,b) {
                    return a === b;
                }
                break;
            case "!=":
                fun =  function (a,b) {
                    return a != b;
                }
                break;
            case ">":
                fun =  function (a,b) {
                    return a > b;
                }
                break;
            case "<":
                fun =  function (a,b) {
                    return a < b;
                }
                break;
            case "<=":
                fun =  function (a,b) {
                    return a <= b;
                }
                break;
            case ">=":
                fun =  function (a,b) {
                    return a >= b;
                }
                break;
            default:
                fun =  function (a,b) {
                    return a === b;
                }
                break;
        }
        jsonArr[i]["func"] = fun;
    }
    var resArr = [];
    if (validatenull(rowIndexs)){
        var rows = getRowIndexStr(detailNumber);
        for(let i=0;i<rows.length;i++){
            var res = true;
            for(let j=0;j<jsonArr.length;j++){
                var fieldId = getFieldId(jsonArr[j].col,true,detailNumber);
                var tempFunc = jsonArr[j]["func"];
                if($.isNumeric(WfForm.getFieldValue(fieldId+"_"+rows[i]))){
                    var vall = parseFloat(WfForm.getFieldValue(fieldId+"_"+rows[i]));
                    var rrr = tempFunc(vall,parseFloat(jsonArr[j].val))
                    if (jsonArr[j].and){
                        res = res&& rrr;
                    }else{
                        res = res||rrr;
                    }
                }else{
                    var vall = WfForm.getFieldValue(fieldId+"_"+rows[i]);
                    var rrr = tempFunc(vall,jsonArr[j].val)
                    if (jsonArr[j].and){
                        res = res&& rrr;
                    }else{
                        res = res||rrr;
                    }
                }
            }
            resArr.push(res);
            if (!res){
                nopassedline.push(rows[i])
            }
        }
    }else{
        var rows = rowIndexs.split(",");
        for(let i=0;i<rows.length;i++){
            var res = true;
            for(let j=0;j<jsonArr.length;j++){
                var fieldId = getFieldId(jsonArr[j].col,true,detailNumber);
                var tempFunc = jsonArr[j]["func"];
                if($.isNumeric(WfForm.getFieldValue(fieldId+"_"+rows[i]))){
                    var vall = parseFloat(WfForm.getFieldValue(fieldId+"_"+rows[i]));
                    var rrr = tempFunc(vall,parseFloat(jsonArr[j].val))
                    if (jsonArr[j].and){
                        res = res&& rrr;
                    }else{
                        res = res||rrr;
                    }
                }else{
                    var vall = WfForm.getFieldValue(fieldId+"_"+rows[i]);
                    var rrr = tempFunc(vall,jsonArr[j].val)
                    if (jsonArr[j].and){
                        res = res&& rrr;
                    }else{
                        res = res||rrr;
                    }
                }
            }
            resArr.push(res);
            if (!res){
                nopassedline.push(rows[i])
            }
        }
    }
    console.log(nopassedline);//打印不满足的明细行标识
    if (isAlert&&nopassedline.length>0){
        var hangs = [];
        for(var i=0;i<nopassedline.length;i++){
            hangs.push(WfForm.getDetailRowSerailNum("detail_"+detailNumber, nopassedline[i]));
        }
        if (validatenull(extraMsg)){
            extraMsg = "不满足条件!"
        }
        msgError("明细表 "+detailNumber+" 第 "+hangs.join("、")+" 行"+extraMsg,3);
    }
    if (isall){
        if (validatenull(setCol)){
            var _result = true;
            for(let i=0;i<resArr.length;i++){
                _result = _result&&resArr[i];
            }
            return _result;
        }else{
            var _result = true;
            for(let i=0;i<resArr.length;i++){
                _result = _result&&resArr[i];
            }
            if (_result){
                setFieldValueOA(setCol,"1");
            }else{
                setFieldValueOA(setCol,"0");
            }
            return _result;
        }
    }else{
        if (validatenull(setCol)){
            var _result = false;
            for(let i=0;i<resArr.length;i++){
                _result = _result||resArr[i];
            }
            return _result;
        }else{
            var _result = false;
            for(let i=0;i<resArr.length;i++){
                _result = _result||resArr[i];
            }
            if (_result){
                setFieldValueOA(setCol,"1");
            }else{
                setFieldValueOA(setCol,"0");
            }
            return _result;
        }
    }
}
/**
 * 根据指定条件判断明细表某字段在所有明细行都满足条件  满足的话为setCol赋值1 否则赋值0
 * @param detailNumber  明细表号
 * @param targetCol  取值用来做判读的字段名
 * @param targetVal  与用来做判断的字段对比的值
 * @param setCol  要设置的字段名  如果不设置setCol 则整个方法会返回校验的结果 true 或 false
 * @param expression  比较表达式  如>= ；可不填 默认 =
 * @param rowIndexs  需要校验的明细行号  不写默认每行都校验
 */
function checkDetailFieldIsAllThisVal(detailNumber,targetCol,targetVal,setCol,expression,rowIndexs){
    var fun = function (a,b) {
        return a === b;
    };
    switch (expression) {
        case "=":
            fun = function (a,b) {
                return a === b;
            }
            break;
        case "!=":
            fun =  function (a,b) {
                return a != b;
            }
            break;
        case ">":
            fun =  function (a,b) {
                return a > b;
            }
            break;
        case "<":
            fun =  function (a,b) {
                return a < b;
            }
            break;
        case "<=":
            fun =  function (a,b) {
                return a <= b;
            }
            break;
        case ">=":
            fun =  function (a,b) {
                return a >= b;
            }
            break;
        default:
            fun =  function (a,b) {
                return a === b;
            }
            break;
    }
    var time;
    if (validatenull(time)){
        time = 300;
    }else{
        time = parseInt(time);
    }
    var fieldId = getFieldId(targetCol,true,detailNumber);
    if (validatenull(setCol)){
        var rows = [];
        if (validatenull(rowIndexs)){
            rows = getRowIndexStr(detailNumber);
        }else {
            rows = rowIndexs.split(",");
        }
        if (rows.length<=0){
            return false
        }else{
            for(var i=0;i<rows.length;i++){
                if (!fun(WfForm.getFieldValue(fieldId+"_"+rows[i]),targetVal)){
                    return false;
                }
            }
            return true;
        }
    }else{
        var interval_checkDetailFieldIsAllThisVal_OA = setInterval(function (){
            var rows = [];
            if (validatenull(rowIndexs)){
                rows = getRowIndexStr(detailNumber);
            }else {
                rows = rowIndexs.split(",");
            }
            if (rows.length<=0){
                setFieldValueOA(setCol,"0");
            }else{
                for(var i=0;i<rows.length;i++){
                    if (!fun(WfForm.getFieldValue(fieldId+"_"+rows[i]),targetVal)){
                        setFieldValueOA(setCol,"0");
                        return false;
                    }
                }
                setFieldValueOA(setCol,"1");
            }
        },time);
    }
}

/**
 * 获取指定行标识以外的剩余行标识
 * @param detailNumber  明细表号码
 * @param excludesRowIndexs  需要排除的明细行标识串 如'0,1,5'
 * @returns {T[]|*|*[]}
 */
function getExcludeRows(detailNumber,excludesRowIndexs){
    var rows = getRowIndexStr(detailNumber);
    var excludes = excludesRowIndexs.split(",");
    if (validatenull(excludesRowIndexs)){
        excludes = [];
    }
    if (validatenull(excludes)){
        return rows;
    }
    return rows.filter(element => !excludes.includes(element));
}

/**
 * 触发对应字段col的字段联动  可以使主表或者明细表字段
 * @param col   指定的字段
 * @param rowIndex  明细行号 可不填   如果需要指定触发某几行的字段联动可以这样指定 0,1,2
 * @param detailNumber  明细表号 可不填  不同明细表出现相同名称字段col时需要指定
 */
function triggerLink(col,rowIndex,detailNumber){
    const json = getFieldIdAndDetail(col);
    if (json.isDetail){//明细表字段
        if (validatenull(rowIndex)){
            if (validatenull(detailNumber)){
                var rows = getRowIndexStr(json.detailNumber);
                for(let i=0; i<rows.length; i++){
                    WfForm.triggerFieldAllLinkage(json.id+"_"+rows[i]);  //主表字段
                }
            }else {
                var rows = getRowIndexStr(detailNumber);
                var id = getFieldId(col,true,detailNumber);
                for(let i=0; i<rows.length; i++){
                    WfForm.triggerFieldAllLinkage(id+"_"+rows[i]);  //主表字段
                }
            }
        }else{
            rowIndex = rowIndex.toString();
            rows = rowIndex.split(",")
            if (validatenull(detailNumber)){
                for(let i=0; i<rows.length; i++){
                    WfForm.triggerFieldAllLinkage(json.id+"_"+rows[i]);  //主表字段
                }
            }else {
                var id = getFieldId(col,true,detailNumber);
                for(let i=0; i<rows.length; i++){
                    WfForm.triggerFieldAllLinkage(id+"_"+rows[i]);  //主表字段
                }
            }
        }
    }else{
        WfForm.triggerFieldAllLinkage(json.id);  //主表字段
    }
}

/**
 * 根据明细行标识获取明细行序号
 */
function getXh(detailNumber,rowIndex){
    return WfForm.getDetailRowSerailNum("detail_"+detailNumber, rowIndex);
}
//**************************************业务处理end*****************************************//

//************************************日期处理start******************************************//

/**
 * 日期格式化转字符串
 * @param date
 * @param fmt
 * @returns {*}
 */
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// dateformat(new Date(),"yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// dateformat(new Date(),"yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
function dateformat(date,fmt) {
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * des 获取当前时间，格式YYYYMMDD
 * @returns {number}
 */
function getDateNow() {
    var date = new Date();
    var year = date.getFullYear();//年
    var month = date.getMonth() + 1;//月
    var strDate = date.getDate(); //日
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year.toString()  + month.toString()  + strDate.toString();
    return currentdate;
}

/**
 * des 获取去年今天时间，格式YYYYMMDD
 * @returns {number}
 */
function getDateLastYearNow() {
    // 获取当前时间
    var currentDate = new Date();
// 减去一年
    currentDate.setFullYear(currentDate.getFullYear() - 1);
    return dateformat(currentDate,'yyyyMMdd')
    /*var date = new Date();
    var year = date.getFullYear()-1;//年
    var month = date.getMonth() + 1;//月
    var strDate = date.getDate(); //日
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year.toString()  + month.toString()  + strDate.toString();
    return currentdate;*/
}


/**
 * 日期浏览框范围设置
 * @param col   指定的日期浏览字段
 * @param start  填写时间范围开始的天数或者日期字符串  如-999 指距今天999天前   或'2019-12-31'
 * @param end    填写间范围结束的天数或日期字符串   如999 指距今天999天后   或'2019-12-31'
 * @param detailNumber   明细表号码  如果不是明细表或者是明细表但是名称不重复可以不填
 * @param rowIndex    明细表行标识  不填默认每一行都设置
 */
function setDateRange(col,start,end,detailNumber,rowIndex){
    if (validatenull(start)){
        start = -9999
    }
    if (validatenull(end)){
        end = 0;
    }
    var id = getFieldId(col,true,detailNumber);
    if (validatenull(rowIndex)){
        WfForm.controlDateRange(id, start, end);
    }else{
        WfForm.controlDateRange(id+'_'+rowIndex, start, end);
    }
}


/**
 * sid日期1、eid日期2规则校验  用于判断日期1和日期2的关系
 * @param sid
 * @param eid
 * @param condition  自定义条件值 默认规则为前者应小于等于后者  可选规则如下
 * >  前者必须大于后者即前者日期必须早于后者日期
 * >= 前者必须大于等于后者即前者日期必须早于或等于后者日期
 * <  前者必须小于后者即前者日期必须晚于后者日期
 * <=  前者必须小于等于后者即前者日期必须晚于或等于后者日期（这是默认规则）
 * =  前者必须等于于后者
 * !=  前者必须不等于于后者
 * n   前者日期必须晚于后者日期n天
 * >n  前者日期必须晚于后者日期n天 同上
 * <n  前者日期必须早于后者日期n天
 * @param msg
 * 用法示例   setDateBind('qwksgzsj','qwgzjssj',"开始时间必须小于结束时间!",'<=')
 * 此处表示qwksgzsj对应的时间必须早于或等于qwgzjssj对应的时间  否则就会弹出提示“开始时间必须小于结束时间！”且清空掉正在选择的时间浏览框
 */
function setDateBind(sid,eid,msg,condition){
    setTimeout(function (){
        var flag1 = $("div[data-fieldmark='"+getFieldId(sid)+"']").find('.wea-date-picker').length
        var flag2 =$("div[data-fieldmark='"+getFieldId(eid)+"']").find('.wea-date-picker').length
        if (flag1==0){
            msgError("所绑定的字段"+sid+"不是日期字段，请重新绑定!");
            return false;
        }
        if (flag2==0){
            msgError("所绑定的字段"+eid+"不是日期字段，请重新绑定!");
            return false;
        }
        if (validatenull(msg)){
            msg = "所选日期不符合条件!";
        }
        if (validatenull(condition)){
            condition = "<=";
        }
        var fun = function (a,b) {
            return a > b;
        };
        switch (condition) {
            case "=":
                fun = function (a,b) {
                    return Math.floor(Math.abs(a.getTime() - b.getTime()) / (1000 * 3600 * 24))!=0;
                }
                break;
            case "!=":
                fun =  function (a,b) {
                    return Math.floor(Math.abs(a.getTime() - b.getTime()) / (1000 * 3600 * 24))==0;
                }
                break;
            case ">":
                fun =  function (a,b) {
                    return a <= b;
                }
                break;
            case "<":
                fun =  function (a,b) {
                    return a >= b;
                }
                break;
            case "<=":
                fun =  function (a,b) {
                    return a > b;
                }
                break;
            case ">=":
                fun =  function (a,b) {
                    return a < b;
                }
                break;
        }
        //判断是否包含数字
        const integerPattern = /\b-?\d+\b/g;
        var days = condition.match(integerPattern) || [];
        if (days.length>0){//存在数字 并取出
            days = days.map(Number);
            var bds = condition.replace(days[0],"");
            var n = days[0]
            switch (bds){
                case "":
                    fun = function (a,b) {
                        if (a<=b){
                            return true;
                        }
                        return Math.floor(Math.abs(a.getTime() - b.getTime()) / (1000 * 3600 * 24))<=n;
                    }
                    break;
                case ">":
                    fun = function (a,b) {
                        if (a<=b){
                            return true;
                        }
                        var xc = Math.floor(Math.abs(a.getTime() - b.getTime()) / (1000 * 3600 * 24));
                        return xc<=n;
                    }
                    break;
                case "<":
                    fun = function (a,b) {
                        if (a>=b){
                            return true;
                        }
                        var xc = Math.floor(Math.abs(a.getTime() - b.getTime()) / (1000 * 3600 * 24));
                        return xc<=n;
                    }
                    break;
                default:
                    fun = function (a,b) {
                        return a < b;
                    }
                    break;
            }
        }
        setFieldListener(sid,function(obj,id,value){
            var e = getFieldValue(eid)
            if(validatenull(e)||validatenull(value)){
                return "";
            }else{
                let date1;
                let date2;
                try{
                    date1 = new Date(value);
                }catch (e){
                    msgError("所绑定日期格式字段值不是日期格式(yyyy-MM-dd或yyyy/MM/dd)");
                    return false;
                }
                try{
                    date2 = new Date(e);
                }catch (e){
                    msgError("所绑定日期格式字段值不是日期格式(yyyy-MM-dd或yyyy/MM/dd)");
                    return false;
                }
                if(fun(date1,date2)){
                    msgError(msg);
                    setFieldValueOA(sid,"");
                    return false;
                }
            }
        })
        setFieldListener(eid,function(obj,id,value){
            var s = getFieldValue(sid)
            if(validatenull(s)||validatenull(value)){
                return "";
            }else{
                let date1 = new Date(s);
                let date2 = new Date(value);
                try{
                    date1 = new Date(s);
                }catch (e){
                    msgError("所绑定日期格式字段值不是日期格式(yyyy-MM-dd或yyyy/MM/dd)");
                    return false;
                }
                try{
                    date2 = new Date(value);
                }catch (e){
                    msgError("所绑定日期格式字段值不是日期格式(yyyy-MM-dd或yyyy/MM/dd)");
                    return false;
                }
                if(fun(date1,date2)){
                    msgError(msg);
                    setFieldValueOA(eid,"");
                    return false;
                }
            }
        })
    },1200)
}

/**
 * 格式化特殊时间字符串为标准格式
 * @param dateStr
 * @returns {*|string}
 */
function formatDateS1(dateStr){
    if (validatenull(dateStr)||dateStr.length<=2){
        return "";
    }
    if (!dateStr.startsWith("0")){
        return dateStr;
    }
    dateStr =  dateStr.substr(2,10);
    var arr = dateStr.split("-");
    var year = "20"+arr[2];
    var mon = arr[1];
    var day = arr[0];
    return year+"-"+mon+"-"+day;
}

/**
 * 校验时间字符串是否是符合给定的格式  默认格式为yyyy-MM-dd
 * @param dateStr  时间字符串
 * @param expectedFormat  时间格式字符串
 * @returns {boolean}  是否符合格式
 */
function isValidDateFormat(dateStr, expectedFormat = 'yyyy-MM-dd') {
    // 正则表达式模式对应预期的日期格式
    const formatPattern = {
        'yyyy': '\\d{4}', // 四位数年份
        'MM': '(0[1-9]|1[0-2])', // 两位数月份，带前导零
        'dd': '(0[1-9]|[12][0-9]|3[01])', // 两位数日期，带前导零
        // 添加更多格式符（如hh:mm:ss等）以支持更复杂的时间格式验证
    };

    // 替换预期格式中的占位符为对应的正则表达式片段
    const regexPattern = expectedFormat.replace(/yyyy|MM|dd/gi, match => formatPattern[match]);

    // 使用正则表达式测试输入字符串是否符合预期格式
    return new RegExp(`^${regexPattern}$`).test(dateStr);
}

//************************************日期处理end******************************************//

//**********************************字符串处理start****************************************//
/**
 * 判断字符串str或数组是否包含p
 * @param str
 * @param p
 * @returns {boolean}
 */
function contains(str,p){
    if(validatenull(str)){
        return false;
    }
    var _str = str.toString();
    return _str.indexOf(p)>-1;
}



/**
 * 判断对象是否为空
 * @param val
 * @returns {boolean}
 */
function validatenull(val) {
    if (typeof val == 'string'){
        if (val==""||val==undefined||val==null){
            return true;
        }
    }
    if (typeof val == 'boolean') {
        return false;
    }
    if (typeof val == 'number') {
        return false;
    }
    if (val instanceof Array) {
        if (val.length == 0) return true;
    } else if (val instanceof Object) {
        if (JSON.stringify(val) === '{}'||JSON.stringify(val) === "\"\""){
            return true;
        }
    } else {
        if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
        return false;
    }
    return false;
}

function isEmptyFunction(func) {
    const source = func.toString();
    const trimmedSource = source.trim();
    const functionBodyStart = trimmedSource.indexOf('{') + 1;
    const functionBodyEnd = trimmedSource.lastIndexOf('}');
    const functionBody = trimmedSource.substring(functionBodyStart, functionBodyEnd);

    // 去除注释和空白字符
    const cleanedBody = functionBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '').trim();

    // 如果清理后的函数体为空，则函数为空
    return cleanedBody === '';
}

/**
 * 判断是否为空
 * @param obj
 * @returns {boolean}
 */
function isBlank(obj){
    return validatenull(obj);
}

/**
 * 判断是否非空
 * @param obj
 * @returns {boolean}
 */
function isNotBlank(obj){
    return !validatenull(obj);
}

/**
 * 根据明细行序号生成四位代码 如序号为1 则生成代码为0001
 * @param xh
 * @param mode 4 3 2  三种模式分别为0001、0002、0003 | 001、002、003 | 10、20、30模式
 * @returns {string}
 */
function xh2Code(detailNumber,rowIndex,mode){
    var xh = WfForm.getDetailRowSerailNum("detail_"+detailNumber, rowIndex);    //获取明细detailNumber下标为rowIndex的行序号
    if (xh==-1){
        msgBox("未找到对应明细表"+detailNumber);
        return ;
    }
    switch (mode){
        case 4:
            if (xh>9999){
                return '9999';
            }
            for(var i=0,zeros="";i<4-xh.toString().length;i++){
                zeros+="0";
            }
            return zeros+xh.toString();
        case 3:
            if (xh>999){
                return '999';
            }
            for(var i=0,zeros="";i<3-xh.toString().length;i++){
                zeros+="0";
            }
            return zeros+xh.toString();
        case 2:
            xh = parseInt(xh)*10;
            return xh.toString();
        default:
            if (xh>9999){
                return '9999';
            }
            for(var i=0,zeros="";i<4-xh.toString().length;i++){
                zeros+="0";
            }
            return zeros+xh.toString();
    }
}

/**
 * 生成guid 全大写
 * @returns {string}
 */
function guid(){
    var guid = "";
    for (var i = 1; i <= 32; i++){
        var flag = Math.floor(Math.random() * 10);
        if(flag%2 == 0) {
            //全大写
            var n = Math.floor(flag*2.4) + 65;
            //全小写
            // var n = Math.floor(flag*2.4) + 97;
             n = String.fromCharCode(n);
            guid += n;
        } else {
            guid += flag;
        }
    }
    return guid.toUpperCase();
}

/**
 * 获得参数的类型
 * @param para
 */
function getParaTypeOA(para){
    if (validatenull(para)){
        return null;
    }
    return typeof para;
}

Array.prototype.removeOA=function(item){
    var index = this.indexOf(item);
    if (index>-1){
        this.splice(index,1);
    }
}

/**
 * 智能合并对象
 * @param source
 * @param target
 * @returns {*}
 */
function smartMerge(source,target){
    let tempObj = Object.assign({},source);
    if (validatenull(source)){
        tempObj = {};
    }
    if (typeof tempObj == 'object'&&!validatenull(tempObj)){
        const  keys = Object.keys(tempObj);
        keys.forEach(key=>{
            if (validatenull(tempObj[key])&&!validatenull(target[key])){
                tempObj[key] = target[key]
            }
        });
        const  tarKeys = Object.keys(target);
        tarKeys.forEach(key=>{
            if (!tempObj.hasOwnProperty(key)){
                tempObj[key] = target[key];
            }
        })
        return tempObj;
    }else{
        return target;
    }
}

/**
 * 检查数组是否包含相同元素
 * @param arr1
 * @param arr2
 * @returns {boolean}
 */
function check2ArrHasSameEle(arr1,arr2){
// 将第一个数组转换为Set对象
    var set1 = new Set(arr1);
// 遍历第二个数组并判断每个元素是否在set1中已经存在
    for (let i of arr2) {
        if (set1.has(i)) {
            return true;//有则返回true
        }
    }
}

/**
 * 获取两个数组中重复的元素
 * @param arr1
 * @param arr2
 * @returns {*[]}
 */
function check2ArrHasSameEleAndReturn(arr1,arr2){
// 将第一个数组转换为Set对象
    var set1 = new Set(arr1);
    var arr = []
// 遍历第二个数组并判断每个元素是否在set1中已经存在
    for (let i of arr2) {
        if (set1.has(i)) {
            arr.push(i)
        }
    }
    return arr;
}

/**
 * 格式化字符串
 * @returns {any|null}
 */
String.formatOA = function() {
    if( arguments.length == 0 )
        return null;

    var str = arguments[0];
    for(var i=1;i<arguments.length;i++) {
        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

/**
 * 获取当前访问页面前缀
 * @returns {string}
 */
function getUrlOA(){
    return window.location.protocol + '//' + window.location.host;
}

/**
 * 获取url路径参数
 * @param name  字段key
 * @param url  url路径 可选 不填默认取当前页面的路径
 * @returns {string}  key对应的参数值
 */
function getUrlParamOA(name,url){
    if(validatenull(url)){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.href.substr(1).match(reg);
        if (r!=null)
            return unescape(r[2]);
        return null;
    }else{
        name = name.replace(/[\[\]]/g, '\\$&');
        const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
        const results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }
}

/**
 * json数组去重
 * @param jsonArray
 * @param keys  key的数组，如 ['id', 'name']
 * @returns {any[]}
 */
function deduplicateJSONArray(jsonArray, keys) {
    const map = new Map();

    // 遍历数组
    jsonArray.forEach(item => {
        // 创建一个复合键，通常使用JSON.stringify，但这里为了性能和可读性，手动构造一个字符串
        const key = keys.map(k => item[k]).join('|');

        if (!map.has(key)) {
            // 如果复合键不存在，则添加到结果数组和Map中
            map.set(key, item);
        }
    });

    // 从Map中获取所有值以形成去重后的数组
    return [...map.values()];
}

/**
 * 获取数组最大值
 * @param arr
 * @returns {number}
 */
function getMaxValueFromArray(arr) {
    if (!Array.isArray(arr) || arr.length === 0) {
        throw new Error('Input must be a non-empty array');
    }

    return Math.max(...arr);
}

/**
 * 计算字符串长度  中文按照1  英文和数字按照0.5
 * @param text
 * @returns {number}
 */
function calculateTextLength(text) {
    let length = 0;

    // 遍历字符串中的每个字符
    for (const char of text) {
        // 判断字符类型
        if (/^[\u4e00-\u9fa5]$/.test(char)) { // 中文字符（Unicode范围）
            length += 1;
        } else if (/^[a-zA-Z0-9]$/.test(char)) { // 英文字符和数字
            length += 0.5;
        }
    }

    return length;
}

/**
 * 遍历data中key为key的值并返回
 * @param key
 * @param data
 * @returns {*[]}
 */
function findValuesForKey(key, data) {
    const values = [];
    if (data instanceof String){
        data = JSON.parse(data);
    }
    function recursiveSearch(item) {
        if (typeof item !== 'object' || item === null) {
            return;
        }

        if (Array.isArray(item)) {
            for (const element of item) {
                recursiveSearch(element);
            }
        } else {
            for (const [k, v] of Object.entries(item)) {
                if (k === key) {
                    values.push(v);
                    break;
                } else if (typeof v === 'object' && v !== null) {
                    recursiveSearch(v);
                }
            }
        }
    }

    recursiveSearch(data);
    if (values.length>0){
        return values[0]
    }
    return values;
}

/**
 * 将数组按照key进行分组并计数返回JSON key为key value为计数值
 * @param arr
 * @returns {*}
 */
function countElements(arr) {
    var res =  arr.reduce((accumulator, currentValue) => {
        accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
        return accumulator;
    }, {});
    return res;
}
//**********************************字符串处理end****************************************//
//**********************************Ajax start**********************************************//
/**
 *
 * @param params
 * @param eventKey
 * @param success
 * @param error
 * @param async
 */
function sendPost(params,eventKey,async,success,error){
    let res;
    params = params||{};
    success = success||function (data){
        res = data;
    };
    error = error||function (e){
        console.log(e);
    }
    if (validatenull(async)){
        async = false;
    }
    let paramStr = JSON.stringify(params);
    $.ajax({
        url:"/interface/ESBInterface.jsp",    //请求的url地址
        dataType:"json",   //返回格式为json
        async:async,//请求是否异步，默认为异步，这也是ajax重要特性
        data:{
            eventKey:eventKey,
            params: paramStr
        },    //参数值
        type:"post",   //请求方式
        // contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success:success,
        error:error
    });
    if (!async){
        return JSON.parse(res.result);
    }
}

/**
 * 下载合同PDF文件
 * @param fileName
 * @param realpath
 */
function downloadPDF(fileName,realpath){
    var params = JSON.stringify({
        fileName:fileName,
        realpath:realpath
    });
    $.ajax({
        type: "GET",
        url: '/interface/ESBInterface.jsp',  //pdf文件流的请求接口
        data:{
            eventKey:"downloadPDF",
            params: params
        },
        async: false,
        mimeType: 'text/plain; charset=x-user-defined',//jq ajax请求文件流的方式  （起作用的重点）
        error: function () {
            //alert("网络原因请求失败！");
            msgError("文件下载失败！")
        },
        success: function (res) {
            try{
                var result = JSON.parse(JSON.parse(res).result);
                var  data = result.data;
                const link = document.createElement("a");
                link.href = `data:application/pdf;base64,${data.base64String}`;
                // 对文件名进行URL解码，并确保它是UTF-8编码以避免乱码
                var decodedFileName = decodeURIComponent(data.fileName);
                link.download = decodedFileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }catch (e){

            }
        }
    });
}
/**
 * 发送GET方法
 * @param params   入参
 * @param eventKey  事件标识
 * @param success  成功回调  可不填 则整个函数返回响应结果  function(response){}
 * @param error   失败回调  可不填  function(err){}
 * @param async  可不填 是否异步  默认同步（false）  如果为true则响应结果必须在success回调中response获取
 * @param isCache  可不填 是否开启浏览器缓存  默认不开启  默认过期时间60分钟
 * @param expire 缓存过期时间  分钟
 */
function sendGet(params,eventKey,async,success,error,isCache,expire){
    if (validatenull(expire)){
        expire = 60;
    }
    if (isCache){
        var key = $.createKey(eventKey,params);
        var json = $.getJsonCache(key);
        if (validatenull(json)){
            let res;
            params = params||{};
            success = success||function (data){
                res = data;
            };
            var proxySuccessFunc = function (data){
                $.setCache(key,data,expire)
                success(data);
            }
            error = error||function (e){
                console.log(e);
            }
            if (validatenull(async)){
                async = false;
            }
            let paramStr = JSON.stringify(params);
            $.ajax({
                url:"/interface/ESBInterface.jsp",    //请求的url地址
                dataType:"json",   //返回格式为json
                async:async,//请求是否异步，默认为异步，这也是ajax重要特性
                data:{
                    eventKey:eventKey,
                    params: paramStr
                },    //参数值
                type:"get",   //请求方式
                // contentType: "application/x-www-form-urlencoded; charset=utf-8",
                success:proxySuccessFunc,
                error:error instanceof Function ? error : function (e){
                    console.log(e)
                },
            });
            if (!async){
                $.setCache(key,res.result,expire)
                return JSON.parse(res.result);
            }
        }else{
                let res;
                success = success||function (data){
                    res = data;
                };
            if (async){
                success(json)
            }else{
                return json;
            }
        }
    }else{
        let res;
        params = params||{};
        success = success||function (data){
            res = data;
        };
        error = error||function (e){
            console.log(e);
        }
        if (validatenull(async)){
            async = false;
        }
        let paramStr = JSON.stringify(params);
        $.ajax({
            url:"/interface/ESBInterface.jsp",    //请求的url地址
            dataType:"json",   //返回格式为json
            async:async,//请求是否异步，默认为异步，这也是ajax重要特性
            data:{
                eventKey:eventKey,
                params: paramStr
            },    //参数值
            type:"get",   //请求方式
            // contentType: "application/x-www-form-urlencoded; charset=utf-8",
            success:success instanceof Function ? success : function (data){
                console.log(data)
            },
            error:error instanceof Function ? error : function (e){
                console.log(e)
            },
        });
        if (!async){
            return JSON.parse(res.result);
        }
    }
}

/**
 * oa执行自定义sql
 * @param sqlid   后台配置的sqlid
 * @param sqlParams 要传输的参数  多个逗号隔开
 * @param callbackName   回调方法名称  如果需要执行回调的话可以填写此参数 不填写方法默认返回整个请求的返回值  填写了则会调用callbackName  入参为返回结果
 * @param eventKey   事件key  不填默认 eventexecutesql
 */
function sendSql(sqlId,sqlParams,callbackName,eventKey){
    if(validatenull(sqlId)){
        msgError("sqlId为空禁止调用!");
        return ;
    }
    if (!validatenull(sqlParams)){
        sqlParams = encodeURIComponent(sqlParams);
    }
    if (validatenull(eventKey)){
        eventKey = "eventexecutesql";
    }
    if (validatenull(callbackName)){
        callbackName = "";
    }
    let param = {};
    param['ClientId'] = 'com.gaoce.jt.oa';
    param['OperationCode'] = 'com.gaoce.jt.oa.jsonp.executesql';
    param['callback'] = callbackName;
    param['sqlId'] = sqlId;
    param['sqlParams'] = sqlParams;
    var res = sendPost(param,eventKey);
    var data = res.data.body.data;
    if (data!=="非法请求!"){
        data = JSON.parse(data);
    }
    if (!validatenull(callbackName)){
        if (window[callbackName] instanceof Function){
            window[callbackName](data);
        }else if (callbackName instanceof Function){
            callbackName(data);
        }else {
            return data;
        }
    }else{
        return data;
    }
}

/**
 * 异步调用sendSql
 * @param sqlId
 * @param sqlParams
 * @param callbackName
 * @param eventKey
 * @param isCache 是否开启缓存
 */
function sendSqlAsync(sqlId,sqlParams,callbackName,eventKey,isCache,expire){
    if (!validatenull(sqlParams)){
        sqlParams = encodeURIComponent(sqlParams);
    }
    if (validatenull(eventKey)){
        eventKey = "eventexecutesql";
    }
    if (validatenull(callbackName)){
        callbackName = "";
    }
    let param = {};
    param['ClientId'] = 'com.gaoce.jt.oa';
    param['OperationCode'] = 'com.gaoce.jt.oa.jsonp.executesql';
    param['callback'] = 'callbackName';
    param['sqlId'] = sqlId;
    param['sqlParams'] = sqlParams;
    sendGet(param,eventKey,true,callbackName,null,isCache,expire);
}

/**
 * 给指定人（或多人转发流程） 发送阅知
 * @param forwardPersonWorkcode  工号，多个用,隔开，如“A1234,A5678”
 * @param requesid   流程ID  可不填 默认取本页面的流程ID
 */
function sendReadKnow(forwardPersonWorkcode,requestid){
    var currentUser = getCurrentUser();
    var currentRequestId = currentUser.requestid;
    if (validatenull(currentRequestId)&&validatenull(requestid)){
        msgError("未设置或获取到requesid!无法发送阅知!");
        return;
    }
    let params = {};
    params["apiType"] = "forward";
    params["workcode"] = currentUser.workcode;//当前登录人工号
    params["forwardFlag"] = 1;
    params["forwardPersonWorkcode"] = forwardPersonWorkcode;
    params["requestId"] = validatenull(requestid)?currentRequestId:requestid;
    var res = sendPost(params,"oa_workflow_forward");//同步执行
    console.log(res);
}

/**
 * 向角色内人员发送阅知
 * @param roleName 角色名称
 * @param requestid  流程ID  可不填 默认取本页面的流程ID
 */
function sendReadKnow2Role(roleName,requestid){
    var users = getRoleUsers(roleName);
    if (validatenull(users)){
        console.log("该角色下没有配置人员!")
        return;
    }
    var workcodearr = [];
    for(var i=0;i<users.length;i++){
        workcodearr.push(users[i].workcode)
    }
    var currentUser = getCurrentUser();
    var currentRequestId = currentUser.requestid;
    if (validatenull(currentRequestId)&&validatenull(requestid)){
        msgError("未设置或获取到requesid!无法发送阅知!");
        return;
    }
    let params = {};
    params["apiType"] = "forward";
    params["workcode"] = currentUser.workcode;//当前登录人工号
    params["forwardFlag"] = 1;
    params["forwardPersonWorkcode"] = workcodearr.join(",");
    params["requestId"] = validatenull(requestid)?currentRequestId:requestid;
    var res = sendPost(params,"oa_workflow_forward");//同步执行
    console.log(res);
}

/**
 * 重新设置浏览框字段显示值
 * @param detailNumber  明细表号
 * @param col   想要修改的字段名
 * @param sqlid  依据的sqlid
 */
function setShowNameDetail(detailNumber,col,sqlid){
    if (validatenull(detailNumber)){
        msgError("请输入明细表标识号");
        return;
    }
    if (validatenull(col)){
        msgError("请输入想要修改显示值的列明");
        return;
    }
    if (validatenull(sqlid)){
        msgError("请输入未设置查询语句sqlid");
        return;
    }
     var rows = getRowIndexStr(detailNumber);
    if (rows.length===0){
        return;
    }
    for(let i=0;i<rows.length;i++){
        sendSqlAsync(sqlid,getFieldValue(col,rows[i],detailNumber),function (data){//异步查询优化使用体验
            var res = data.result
            res = JSON.parse(res);
            var c = res.data.body.data;
            var arr = JSON.parse(c);
            if(!validatenull(arr)&&arr.length>0){
                var obj = arr[0];
                var val = obj[ Object.keys(obj)[0] ]
                setFieldValueOA(col,getFieldValue(col,rows[i],detailNumber)+'|'+val,rows[i],detailNumber);
            }
        });
    }
}

/**
 * 获取指定角色的人员信息 不包含管理員
 * @param roleName
 * @returns {*}
 */
function getRoleUsers(roleName){
    //roleName = encodeURIComponent(roleName)
    if (ENV_ACTIVE_OA==="PROD"){
        return sendSql('T7OET3731AJJJ9A99EAE9933E97OJ1O7',roleName)
    }else if(ENV_ACTIVE_OA==="DEV"){
        return sendSql('E5EO7TJ539995JAT9131AE5ATT9T919J',roleName)
    }
}

/**
 * 根据工号查询用户信息
 * @param workcode
 * @returns {*}
 */
function getUserInfoByWorkcode(workcode){
     return sendSql('553AT5A3ETJ7TJJTA55J59391135AT93',workcode);
}

/**
 * 根据角色、工号获取人员id 或者部门id如果为部门id则会自动获取部门经理id
 * @param strs
 * @returns {*[]}
 */
function getUserIdsByRoleOrWorkcode(strs){
    if (validatenull(strs)){
        return []
    }else if (strs.startsWith(",")){
        strs = strs.replace(',','')
    }
    if (validatenull(strs)){
        return []
    }
    const strArr = strs.split(",");
    let peopleArr = [];
    for(let i=0; i<strArr.length; i++){
        if(/[\u4e00-\u9fa5]/.test(strArr[i])){//角色
            var arr = getRoleUsers(strArr[i]);
            for(let j=0; j<arr.length; j++){
                if (!peopleArr.includes(arr[j].id.toString()))
                peopleArr.push(arr[j].id.toString())
            }
        }else if($.isNumeric(strArr[i])){//id
            var id = sendSql('O99O1O5717595J31T9EOO713J97AT3O1',strArr[i])[0].id.toString()
            if (!peopleArr.includes(id))
            peopleArr.push(id.toString());
        }else{//工号
            var arr = getUserInfoByWorkcode(strArr[i])
            if (!peopleArr.includes(arr[0].id.toString()))
            peopleArr.push(arr[0].id.toString())
        }
    }
    return peopleArr;
}

/**
 * 获取当前登录人信息
 */
function getCurrentUser(){
    var baseInfo = WfForm.getBaseInfo();
    var userid = baseInfo.f_weaver_belongto_userid;//当前登录人id
    if (userid=="1"){
        var requestid = baseInfo.requestid;
        return {userid:userid,workcode:"sysadmin",requestid:requestid}
    }
    var workcode = getUserById(userid)[0].workcode;
    var requestid = baseInfo.requestid;
    return {userid:userid,workcode:workcode,requestid:requestid}
}

/**
 * 根据用户userid获取用户信息
 * @param userid
 * @returns {*}
 */
function getUserById(userid){
    return sendSql("1T539997OJJOT97E3O7OJJO9OA7T9E71",userid+","+userid+","+userid)
}

/**
 * 根据用户id获取用户名 多个逗号隔开
 * @param ids
 */
function getUserNameByIds(ids){
    var arr = [];
    var idArr = ids.split(",");
    for(var i=0;i<idArr.length;i++){
        var user = getUserById(idArr[i])
        arr.push(user[0].lastname)
    }
    return arr.join(",")
}

/**
 * 获取申请人userid
 * @param requestid
 * @returns {number}
 */
function getSqrUserid(requestid){
    if (validatenull(requestid)){
        var baseInfo = WfForm.getBaseInfo();
        requestid = baseInfo.requestid;
    }
    var base = sendSql("3T3O33OE977773O715A57OE139OAT533","workflow_requestbase,requestid="+requestid);
    if (!validatenull(base)&&!validatenull(base[0])&&!validatenull(base[0].creater)){
        return base[0].creater
    }else{
        return null;
    }
}

/**
 * 根据用户工号或userid获取用户基本信息
 * @param codeOrid
 */
function getHrmSimpleInfo(codeOrid,async,success,error){
    let res;
    if($.isNumeric(codeOrid)){//userid
        $.ajax({
            url:"/api/hrm/simpleinfo/getHrmSimpleInfo?userid="+codeOrid,    //请求的url地址
            dataType:"json",   //返回格式为json
            async:validatenull(async)?false:async,//请求是否异步，默认为异步，这也是ajax重要特性
            type:"get",   //请求方式
            // contentType: "application/x-www-form-urlencoded; charset=utf-8",
            success:success instanceof Function ? success : function (data){
                res =  data.simpleInfo;
            },
            error:error instanceof Function ? error : function (e){
                console.log(e)
            }
        });
    }else{//工号
        var info = getUserInfoByWorkcode(codeOrid)
        if (validatenull(info)||info.length==0){
            return {}
        }
        $.ajax({
            url:"/api/hrm/simpleinfo/getHrmSimpleInfo?userid="+info[0].id,    //请求的url地址
            dataType:"json",   //返回格式为json
            async:validatenull(async)?false:async,//请求是否异步，默认为异步，这也是ajax重要特性
            type:"get",   //请求方式
            // contentType: "application/x-www-form-urlencoded; charset=utf-8",
            success:success instanceof Function ? success : function (data){
                res = data.simpleInfo;
            },
            error:error instanceof Function ? error : function (e){
                console.log(e)
            }
        });
    }
    if (!async){
        return res;
    }
}

/**
 * 获取当前流程已审批人员列表
 * @param
 * @returns {array}  已操作人员列表不包含机器人
 */
function getOperateList(){
    var users = [];
    var ass = $('.wf-req-sign-list').find('div.wf-req-sign-list-content').find('.operate-name-label').find('a');
    for(var i=ass.length-1;i>=0;i--){
        var userid = $(ass[i]).attr('href').split("(")[1].replace(")","");
        if (userid=='1'){
            users.push({workcode: '', id: 1, lastname: '系统管理员'});
        }else{
            var deptId = parseInt(getUrlParamOA("id",$(ass[i]).parent().next().find("a").attr("href")))
            var deptName = $(ass[i]).parent().next().find("a")[0].textContent;
            var json = getUserById(userid)[0];
            json["did"] = deptId;
            json["dname"] = deptName;
            users.push(json);
        }
    }
    return users;
}

/**
 * 获取流程审批流信息
 * @param mode
 * @param successCallback
 * @returns {*}
 */
function getWorkflowInfo(mode,successCallback){
    var baseInfo = WfForm.getBaseInfo();
    let res;
    $.ajax({
        url:"/api/workflow/layout/getXml",    //请求的url地址
        dataType:"json",   //返回格式为json
        async:false,
        data:{
            "ismonitor":"1",
            "isovertime":"0",
            "requestid":baseInfo.requestid,
            "workflowid":baseInfo.workflowid,'isFromWfForm': true,'isFlowModel': 0,'hasFreeNode':0
        },
        type:"post",   //请求方式
        // contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success: successCallback instanceof Function ? successCallback : function (data){
            if (mode===0||mode==="0"){
                res = data.nodeInfo;
            }else if (mode===1||mode==="1"){
                var nodes = [];
                var keys = Object.keys(data.nodeInfo);
                for(var i=0;i<keys.length;i++){
                    var node = data.nodeInfo[keys[i]];
                    var item = {};
                    item["isCurrentNode"] = node.isCurrentNode;
                    item["nodeName"] = node.nodeName;
                    item["notOperators"] = node.notOperators;
                    item["operators"] = node.operators;   //type 0  具体到人  type 1  角色或系统字段
                    item["viewers"] = node.viewers;
                    nodes.push(item);
                }
                res = nodes;
            }else if (mode===2||mode==="2"){//精细模式
                var nodes = {};
                var passed = [];
                var current = [];
                var maybepass = [];
                var keys = Object.keys(data.nodeInfo);
                for(var i=0;i<keys.length;i++){
                    var node = data.nodeInfo[keys[i]];
                    var item = {};
                    if (node.ntype==="0"){//发起节点
                        item.nodeName = node.nodeName;
                        item.operators = node.operators;
                        nodes["start"] = item
                    }else if (node.ntype==="3"){
                        item.nodeName = node.nodeName;
                        item.operators = node.operators;
                        nodes["end"] = item
                    }
                    if(node.nodeType===0){
                        var item1 = {};
                        item1.nodeName = node.nodeName;
                        item1.operators = node.operators;
                        passed.push(item1)
                    }else if (node.nodeType===2){
                        var item1 = {};
                        item1.nodeName = node.nodeName;
                        //对node.operators中的操作人进行处理  指定人的直接换成指定人  取系统字段的直接换成系统字段值  取角色的换成角色名称  未做待做
                        item1.operators = node.operators;
                        maybepass.push(item1)
                    } else if (node.nodeType===1){
                        var item1 = {};
                        item1.nodeName = node.nodeName;
                        item1.operators = node.operators;
                        current.push(item1)
                    }
                }
                nodes["passed"] = passed;
                nodes["current"] = current;
                nodes["maybepass"] = maybepass;
                res = nodes;
            }else{
                res = data.nodeInfo;
            }
        },
        error:function (e){
            console.log(e)
        }
    });
    return res;
}


/**
 * 根据所给的工号设置多人力资源字段
 * @param workcodes   工号  多个用","隔开
 * @param col   多人力资源或者人力资源字段
 */
function setUserFieldByWorkcodes(col,workcodes){
    if (!validatenull(workcodes)){
        var gharr = workcodes.split(",");
        var sqe = [];
        for(var i=0;i<gharr.length;i++){
            var sqe_temp = getUserInfoByWorkcode(gharr[i]);
            if(!validatenull(sqe_temp)){
                sqe.push(sqe_temp[0].id+"|"+sqe_temp[0].lastname)
            }
        }
        setFieldValueOA(col,sqe.join(","))
    }else{
        setFieldValueOA(col,"");
    }
}

/**
 * 发送jsonp
 * @param url   后台服务路径
 * @param callbackName   回调方法名称
 */
function sendJsonp(url,callbackName){
    if (!url.startsWith("http")&&!url.startsWith("https")){
        msgBox("路径错误!url="+url);
        return;
    }
    var script = document.createElement('script');
    script.type="text/javascript";
    script.src = url+'&callback='+callbackName;
    document.getElementsByTagName("head")[0].appendChild(script);
}


/**
 * 刷新明细表
 * @param detailNumber
 */
function refreshTab(detailNumber,isall){
    if(validatenull(isall)){
        isall = true
    }
    if (validatenull(detailNumber)){
        return;
    }
    var arr = [];
    if (typeof(detailNumber)=='number'){
        arr.push(detailNumber)
    }else{
        arr = detailNumber.split(",");
    }
    //获取到最新的数据  然后将表单DOM更新  res是一个列表
    for(var i=0;i<arr.length;i++){
        var d = parseInt(arr[i]);
        var rrr = getRowIndexStr(arr[i]);
        const tds = $($('#oTable' + (d - 1)).find("tr[data-rowindex='"+rrr[0]+"']")[0]).find("td");
        let field;
        for(var i=0;i<tds.length;i++){
            var fieldname = $($(tds[i]).children()[0]).attr("data-fieldname");
            if (!validatenull(fieldname)){
                field =  fieldname;
                break;
            }
        }
        var info = WfForm.getFieldInfo(getFieldId(field,false,d));
        var tableName = info.tableName;
        if (isall){
            var ids = getDetailRowKey(d);
            var res;
            if(ENV_ACTIVE_OA==="DEV"){
                res = sendSql("OE5799TJ15JJ19T1ET77J91JT77EA9AO",tableName+","+ids.join("|"))
            }else if(ENV_ACTIVE_OA==="PROD"){
                res = sendSql("3T3O33OE977773O715A57OE139OAT533",tableName+","+ids.join("|"))
            }
            updateDetailRowByIdOA(d,res,getRowIndexStr(d))
        }else{
            var obj = getRowIndexStr(d,!isall);
            var hide = obj.hide;
            var ids = [];
            for(var x=0;x<hide.length;x++){
                ids.push(getDetailRowKey(d,hide[x]))
            }
            ids = ids.join("|");
            var res;
            if(ENV_ACTIVE_OA==="DEV"){
                res = sendSql("OE5799TJ15JJ19T1ET77J91JT77EA9AO",tableName+","+ids.join("|"))
            }else if(ENV_ACTIVE_OA==="PROD"){
                res = sendSql("3T3O33OE977773O715A57OE139OAT533",tableName+","+ids.join("|"))
            }
            updateDetailRowByIdOA(d,res,obj.hide)
        }
    }
}

/**
 * 释放预算
 * @param businessCode
 */
function releaseBudgetOA(businessCode){
    var params = {
        "businessCode":businessCode
    }
   return sendGet(params,'yssf',true,function (data){
       if (!validatenull(data.result)){
           var result = JSON.parse(data.result);
           if (result.data.msg=="success"){
               msgSuccess("释放预算成功!")
           }else{
               msgError("释放预算失败!")
           }
       }else{
           msgError("释放预算失败!")
       }
   },function (err){
       msgError("释放预算失败!"+err)
   });
}

/**
 * esb请求转发oa_custom_action服务
 * @param path  oa_custom_action的路径 如/autoUpdate/updateDataProcGrp
 * @param body  请求体json 不是字符串格式
 * @param callback   回调函数  入参为返回值
 */
function esbForward(path,body,callback,async){
    //发送ajax请求
    let param = {};
    //7.主键字段接口名=触发字段变化后的值
    param['path'] = path;
    param['body'] = JSON.stringify(body);
    let paramStr= JSON.stringify(param);
    if (validatenull(async)){
        async = false;
    }
    $.ajax({
        url:"/interface/ESBInterface.jsp",    //请求的url地址
        dataType:"json",   //返回格式为json
        async:async,
        data:{
            eventKey:'esbforwardevent',
            params: paramStr
        },    //参数值
        type:"post",   //请求方式
        success:function(data){
            let resultStr = data.result;
            let result = JSON.parse(resultStr)
            if (callback instanceof Function){
                callback(result);
            }
        },
        error:function(err){
            callback(err);
        }
    });
}

/**
 * 针对浏览框字段的提前渲染  解决浏览按钮字段只有第一页显示正常其他页显示代码的问题  要求明细表分页生效
 * @param detailNumber  明细表号码
 * @param columns   字段 为字符串，如khmc,ck...  多个用逗号隔开
 * @param isDeepRender  是否深度渲染  开启深度渲染如果在首页中未查到相关数据会主动调用接口查询并赋值
 * @param deepConfig 深度查询配置
 * [
 *  {
 *      column: "khmc",
 *      eventkey:"getsapkhxxchsj",
 *      eventjson:"{\"KUNNR\":\"%s\"}",
 *      eventResKey:"NAME1",
 *      sqlid:"JT933A5T7TTE93EE353OTO1J5JT3311A2",
 *      cache:true,  可选 默认开启
 *      expire:30 可选  默认60分钟
 *  }
 * ]
 */
function detailQuickLoading(detailNumber,columns,isDeepRender,deepConfig){
    setTimeout(function (){
        let pages = $("#dTableArea_"+(parseInt(detailNumber)-1)).parent().find(".wf-detail-paging");
        if (pages.length==0){//未分页不执行主动渲染
            return;
        }
        if (validatenull(columns)){
            return;
        }
        window["detailQuickLoadingFlag_OA_"+detailNumber] = false
        let render = setInterval(function (){
            try{
                if (window["detailQuickLoadingFlag_OA_"+detailNumber]){
                    return;
                }
                let pagecontent = $("#dTableArea_"+(parseInt(detailNumber)-1)).parent().find(".wf-detail-paging").find(".ant-pagination-total-text")[0];
                if (pagecontent==null||pagecontent.length==0){
                    return;
                }
                let countTxt = $("#dTableArea_"+(parseInt(detailNumber)-1)).parent().find(".wf-detail-paging").find(".ant-pagination-total-text")[0].textContent;
                if(countTxt=='共0条'){
                    return;
                }
                //是否深度渲染
                if (isDeepRender){
                    //开启深度渲染可能需要提前调用接口查询显示值  相当于提前调用回显事件并赋值
                    window["detailQuickLoadingFlag_OA_"+detailNumber] = true;
                    //获取每页条数  用于获取第一页的数据  因为第一页已加载完毕
                    let ts = $("#dTableArea_"+(parseInt(detailNumber)-1)).parent().find(".wf-detail-paging").find(".ant-select-selection-selected-value")[0].textContent.split(" ")[0];
                    let modelJSON = {};
                    let rows = getRowIndexStr(detailNumber);
                    let colArr = columns.split(",");
                    for(let i=0;i<parseInt(ts)-1;i++){
                        for(let j=0;j<colArr.length;j++){
                            let val = getFieldValue(colArr[j],rows[i],detailNumber);
                            let show = getShowNameOA(colArr[j],rows[i],detailNumber);
                            let item = modelJSON[colArr[j]];
                            if (validatenull(item)){
                                item = {};
                                item[val] = show;
                                modelJSON[colArr[j]] = item;
                            }else{
                                modelJSON[colArr[j]][val] = show;
                            }
                        }
                    }
                    //解析deepConfig并装配查询方法
                    if (!validatenull(deepConfig)&&deepConfig.length>0){
                        for(let i=0;i<deepConfig.length;i++){
                            let item = deepConfig[i];
                            const column = item.column;
                            const eventkey = item.eventkey;
                            const eventjson = item.eventjson;
                            const eventResKey = item.eventResKey;
                            const sqlid = item.sqlid;
                            let cache = item.cache;
                            const expire = item.cache;
                            if (validatenull(cache)){
                                cache = true;
                            }
                            if (cache=='true'||cache===true||validatenull(cache)){
                                cache = true;
                            }else{
                                cache = false;
                            }
                            if (!validatenull(eventkey)){
                                //eventkey
                                window[column+"_"+detailNumber] = function (inStr,rowindex){
                                    sendGet(JSON.parse(eventjson.replace("%s",inStr)),eventkey,true,function (data){
                                        //响应返回结果  根据eventResKey遍历出目标值  然后执行重新赋值
                                        try{
                                            var res = JSON.parse(data.result);
                                            if (res.code==100){//查询成功
                                                var show = findValuesForKey(eventResKey, res.data);
                                                setFieldValueOA(column,inStr+"|"+show,rowindex,detailNumber);
                                            }
                                        }catch (e){
                                            console.error(e)
                                        }
                                    },null,cache,expire)//开启缓存
                                }
                                console.log("deepConfig查询函数【"+column+"_"+detailNumber+"】【event】装配完成");
                            }else if (validatenull(eventkey)&&!validatenull(sqlid)){
                                //sqlid
                                window[column+"_"+detailNumber] = function (inStr,rowindex){
                                    sendSqlAsync(sqlid,inStr,function (data){
                                        try{
                                            var res = JSON.parse(data.result);
                                            if (res.code==100){//查询成功
                                                var val = res.data.body.data;
                                                if (!validatenull(val)&&val.length>0){
                                                    var jjson = JSON.parse(val.replace(/\\/g, ''))
                                                    setFieldValueOA(column,inStr+"|"+Object.values(jjson[0])[0],rowindex,detailNumber);
                                                }
                                            }
                                        }catch (e){
                                            console.error(e)
                                        }
                                    },null,cache,expire);//开启缓存
                                }
                                console.log("deepConfig查询函数【"+column+"_"+detailNumber+"】【sql】装配完成");
                            }
                        }
                    }
                    //首页数据收集完成开始对后续页进行主动赋值
                    for(let i=parseInt(ts);i<(rows.length);i++){
                        for(let j=0;j<colArr.length;j++){
                            let val = getFieldValue(colArr[j],rows[i],detailNumber);
                            let show = getShowNameOA(colArr[j],rows[i],detailNumber);
                            if (!validatenull(val)){
                                var own = modelJSON[colArr[j]][val];
                                if (!validatenull(own)&&show!==own){
                                    setFieldValueOA(colArr[j],val+"|"+own,rows[i],detailNumber)
                                }else if (validatenull(own)){//如果出现了第一页中不存在的val则需要主动查询
                                        window[colArr[j]+"_"+detailNumber](val,rows[i])
                                }
                            }
                        }
                    }
                    window["detailQuickLoadingFlag_OA_"+detailNumber] = false;
                    clearInterval(render);
                }else{
                    window["detailQuickLoadingFlag_OA_"+detailNumber] = true;
                    //获取每页条数  用于获取第一页的数据  因为第一页已加载完毕
                    var ts = $("#dTableArea_"+(parseInt(detailNumber)-1)).parent().find(".wf-detail-paging").find(".ant-select-selection-selected-value")[0].textContent.split(" ")[0];
                    var modelJSON = {};
                    var rows = getRowIndexStr(detailNumber);
                    var colArr = columns.split(",");
                    for(var i=0;i<parseInt(ts)-1;i++){
                        for(var j=0;j<colArr.length;j++){
                            var val = getFieldValue(colArr[j],rows[i],detailNumber);
                            var show = getShowNameOA(colArr[j],rows[i],detailNumber);
                            item = modelJSON[colArr[j]];
                            if (validatenull(item)){
                                item = {};
                                item[val] = show;
                                modelJSON[colArr[j]] = item;
                            }else{
                                modelJSON[colArr[j]][val] = show;
                            }
                        }
                    }
                    //首页数据收集完成开始对后续页进行主动赋值
                    for(i=parseInt(ts);i<(rows.length);i++){
                        for(var j=0;j<colArr.length;j++){
                            var val = getFieldValue(colArr[j],rows[i],detailNumber);
                            var show = getShowNameOA(colArr[j],rows[i],detailNumber);
                            item = modelJSON[colArr[j]];
                            if (!validatenull(val)){
                                var own = modelJSON[colArr[j]][val];
                                if (!validatenull(own)&&show!==own){
                                    setFieldValueOA(colArr[j],val+"|"+own,rows[i],detailNumber)
                                }
                            }
                        }
                    }
                    window["detailQuickLoadingFlag_OA_"+detailNumber] = false;
                    clearInterval(render);
              }
            }catch (e){
                    console.error(e)
                clearInterval(render);
            }
        },500)
    },500)
}

/**
 * 设置选择物料编码自动带出物料其他信息 按自动版本1.0
 * @param detailNumbers  明细表号码  多个用逗号隔开 如 “1,2”
 * @param config 自定义配置 左侧的key不能变  右侧实际字段编码名可以修改 如你的表单中物料编码不叫“wlbm”而是叫“mywlbm”  那么此时就是wlbm:"mywlbm"  以此类推
 * config = {
 *         wlbm:"wlbm", //物料编码字段
 *         wlms:"wlms",//物料描述字段
 *         bb:"bb",//物料版本字段
 *         dj:"dj",//物料单价字段
 *         cgz:"cgz",//采购组字段
 *         wlzj:"wlzj",//物料专家字段
 *         wlzjlb:"wlzjlb",//物料专家类别字段
 *         cgy:"cgy",//采购员字段
 *         wwhst:"wwhst",//未维护视图
 *         wlsx:"wlsx",//物料属性
 *         sszz:"sczznew",//默认取sczznew
 *         gc:"scgcnew"//默认取scgcnew
 *     }
 *     使用方法：
 *     如果不需要指定明细表那么就直接一行代码即可setMaterialInfo();
 *     此时代码会自动判断明细表中是否含有物料编码字段如果有就会增加绑定事件  当物料编码变动时会自动带出上述类型字段（如果有这些字段的话）
 *     如果需要指定那么就可以这样设置
 *     setMaterialInfo(1);
 *     或setMaterialInfo(“1”);
 *     或（多个明细表明细表1、2、4）setMaterialInfo(“1,2,4”);
 */
const JXSDMJSON = {
    "J0":0,
    "J1":0.13,
    "J2":0.09,
    "J3":0.06,
    "J4":0.05,
    "J5":0.03,
    "J6":0.01,
    "J7":0.17,
    "L1":0.05,
    "X0":0,
    "X1":0.13,
    "X2":0.09,
    "X3":0.06,
    "X4":0.03,
    "X5":0.01
}
function setMaterialInfo(detailNumbers,config){
    if ( !validatenull(detailNumbers)&& typeof  detailNumbers == 'number'){
        detailNumbers = detailNumbers.toString();
    }
    if (validatenull(config)){
        config = {};
    }
    config = smartMerge(config,{
        sszz:"sczznew",
        gc:"scgcnew"
    });
    var getWlbm = function (detail){
        if (validatenull(config.wlbm)){
            var wlbm =  WfForm.convertFieldNameToId('wlbm',"detail_"+detail);
            if (validatenull(wlbm)){
                wlbm =  WfForm.convertFieldNameToId('wl',"detail_"+detail);
            }
            if (validatenull(wlbm)){
                wlbm =  WfForm.convertFieldNameToId('wlbh',"detail_"+detail);
            }
            if (validatenull(wlbm)){
                wlbm =  WfForm.convertFieldNameToId('spbm',"detail_"+detail);
            }
            return wlbm;
        }else{
            return config.wlbm;
        }
    }
    var getWlms = function (detail){
        if (validatenull(config.wlms)){
            var wlms =  WfForm.convertFieldNameToId('wlms',"detail_"+detail);
            if (validatenull(wlms)){
                wlms =  WfForm.convertFieldNameToId('wlmc',"detail_"+detail);
            }
            if (validatenull(wlms)){
                wlms =  WfForm.convertFieldNameToId('wlxx',"detail_"+detail);
            }
            if (validatenull(wlms)){
                wlms =  WfForm.convertFieldNameToId('spmc',"detail_"+detail);
            }
            return wlms;
        }else{
            return config.wlms;
        }
    }
    var getBb = function (detail){
        if (validatenull(config.bb)){
            var bb =  WfForm.convertFieldNameToId('bb',"detail_"+detail);
            if (validatenull(bb)){
                bb =  WfForm.convertFieldNameToId('wlbb',"detail_"+detail);
            }
            return bb;
        }else{
            return config.bb;
        }
    }
    var getDw = function (detail){
        var dw =  WfForm.convertFieldNameToId('dw',"detail_"+detail);
        if (validatenull(dw)){
            dw =  WfForm.convertFieldNameToId('wldw',"detail_"+detail);
        }
        if (validatenull(dw)){
            dw =  WfForm.convertFieldNameToId('jldw',"detail_"+detail);
        }
        if (validatenull(dw)){
            dw =  WfForm.convertFieldNameToId('jbjldw',"detail_"+detail);
        }
        return dw;
    }
    var getWldj = function (detail){
        if (validatenull(config.dj)){
            var wldj =  WfForm.convertFieldNameToId('wldj',"detail_"+detail);
            if (validatenull(wldj)){
                wldj =  WfForm.convertFieldNameToId('dj',"detail_"+detail);
            }
            if (validatenull(wldj)){
                wldj =  WfForm.convertFieldNameToId('wsdj',"detail_"+detail);
            }
            if (validatenull(wldj)){
                wldj =  WfForm.convertFieldNameToId('wsdjy',"detail_"+detail);
            }
            if (validatenull(wldj)){
                wldj =  WfForm.convertFieldNameToId('jg',"detail_"+detail);
            }
            if (validatenull(wldj)){
                wldj =  WfForm.convertFieldNameToId('wljg',"detail_"+detail);
            }
            return wldj;
        }else{
            return config.dj;
        }
    }
    var getWlhsdj = function (detail){
        if (validatenull(config.hsdj)){
            var hsdj =  WfForm.convertFieldNameToId('hsdj',"detail_"+detail);
            if (validatenull(hsdj)){
                hsdj =  WfForm.convertFieldNameToId('hsdjy',"detail_"+detail);
            }
            if (validatenull(hsdj)){
                hsdj =  WfForm.convertFieldNameToId('hsj',"detail_"+detail);
            }
            if (validatenull(hsdj)){
                hsdj =  WfForm.convertFieldNameToId('hsjy',"detail_"+detail);
            }
            return hsdj;
        }else{
            return config.hsdj;
        }
    }
    var getCgz = function (detail){
        if (validatenull(config.cgz)){
            var cgz =  WfForm.convertFieldNameToId('cgz',"detail_"+detail);
            if (validatenull(cgz)){
                cgz =  WfForm.convertFieldNameToId('cgzdm',"detail_"+detail);
            }
            if (validatenull(cgz)){
                cgz =  WfForm.convertFieldNameToId('cgzmc',"detail_"+detail);
            }
            return cgz;
        }else{
            return config.cgz;
        }
    }
    var getWlzjlb = function (detail){
        if (validatenull(config.wlzjlb)){
            var wlzjlb =  WfForm.convertFieldNameToId('wlzjlb',"detail_"+detail);
            if (validatenull(wlzjlb)){
                wlzjlb =  WfForm.convertFieldNameToId('wlzjlx',"detail_"+detail);
            }
            return wlzjlb;
        }else{
            return config.wlzjlb;
        }
    }
    var getWlzj = function (detail){
        if (validatenull(config.wlzj)){
            var wlzj =  WfForm.convertFieldNameToId('wlzj',"detail_"+detail);
            return wlzj;
        }else{
            return config.wlzj;
        }
    }
    var getCgy = function (detail){
        if (validatenull(config.cgy)){
            var cgy =  WfForm.convertFieldNameToId('cgy',"detail_"+detail);
            return cgy;
        }else{
            return config.cgy;
        }
    }
    var getWwhst = function (detail){
        if (validatenull(config.wwhst)){
            var wwhst =  WfForm.convertFieldNameToId('wwhst',"detail_"+detail);
            if (validatenull(wwhst)){
                wwhst =  WfForm.convertFieldNameToId('whst',"detail_"+detail);
            }
            if (validatenull(wwhst)){
                wwhst =  WfForm.convertFieldNameToId('whdst',"detail_"+detail);
            }
            return wwhst;
        }else{
            return config.wwhst;
        }
    }
    var getWlsx = function (detail){
        if (validatenull(config.wlsx)){
            var wlsx =  WfForm.convertFieldNameToId('wlsx',"detail_"+detail);
            return wlsx;
        }else{
            return config.wlsx;
        }
    }
    var getCgzq = function (detail){
        if (validatenull(config.cgzq)){
            var cgzq =  WfForm.convertFieldNameToId('cgzq',"detail_"+detail);
            if (validatenull(cgzq)){
                cgzq =  WfForm.convertFieldNameToId('gdcgzqt',"detail_"+detail);
            }
            if (validatenull(cgzq)){
                cgzq =  WfForm.convertFieldNameToId('gdcgzq',"detail_"+detail);
            }
            return cgzq;
        }else{
            return config.cgzq;
        }
    }
   if (validatenull(detailNumbers)){//如果为空就自动搜索表单上所有有物料编码的明细表自动添加配置
        if ($('.excelDetailTable').length==0){
            return;
        }else {
            var details = "1,2,3,4,5,6,7,8,9,10".split(",");//对明细表进行分组
            for(var i=0;i<details.length;i++){
                const temp = details[i];
                if ($.isNumeric(temp)){//防止瞎写  只处理数字的
                    var wlbmid =  getWlbm(temp);
                    if (validatenull(wlbmid)){
                        continue;
                    }else{
                        //绑定字段变动事件
                        //先查询该字段有没有绑定事件
                        var oldEvent = WfForm.__detailFieldChangeFnObj[wlbmid];
                        if (validatenull(oldEvent)){//如果没有直接执行绑定
                            setFieldListener(wlbmid,function (id,rowIndex,value){
                                var wlmsid = getWlms(temp);
                                var dwid = getDw(temp);
                                var djid = getWldj(temp);
                                var wlbbid = getBb(temp);

                                var cgzid = getCgz(temp);
                                var wlzjlbid = getWlzjlb(temp);
                                var wlzjid = getWlzj(temp);
                                var cgyid = getCgy(temp);
                                var wwhstid = getWwhst(temp)
                                var wlsxid = getWlsx(temp)
                                var cgzqid = getCgzq(temp)
                                var hsdjid = getWlhsdj(temp)
                                if (validatenull(value)){
                                    //清空目标字段值
                                    WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(djid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(cgyid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:null});
                                    return;
                                }
                                let param1 = {};
                                //7.主键字段接口名=触发字段变化后的值
                                param1['MATNR'] = value;
                                param1['DATE_BEGIN'] = getDateLastYearNow();
                                param1['DATE_END'] = getDateNow();
                                param1['ClientId'] = 'com.gaoce.jt.oa';
                                param1['OperationCode'] = 'com.gaoce.jt.sap.mm001.MatnrQuery';
                                sendGet(param1,'sapwlmxsjcxsj',true,function(data){
                                    var result = JSON.parse(data.result);
                                    if (!validatenull(wlmsid)){
                                        WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:result.data.list[0].MAKTX});
                                    }
                                    if (!validatenull(dwid)){
                                        WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:result.data.list[0].MEINS});
                                    }
                                    if (!validatenull(wlbbid)){
                                        WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:result.data.list[0].ZWLBB});
                                    }
                                    if (!validatenull(wlzjlbid)){//物料专家类型
                                        WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:result.data.list[0].ZZJD});
                                    }
                                    if (!validatenull(cgzid)){//采购组
                                        WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:result.data.list[0].EKGRP});
                                    }
                                    if (!validatenull(cgzqid)){//固定采购周期
                                        WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:result.data.list[0].APLFZ});
                                    }
                                    if (!validatenull(wlsxid)){//物料属性
                                        var tscg = result.data.list[0].SOBSL;
                                        var wlsx = result.data.list[0].BESKZ;
                                        if(wlsx=='F'&&tscg=='30'){
                                            wlsx='委外';
                                        }else if(wlsx=='F'&&tscg!='30'){
                                            wlsx='外购';
                                        }else if(wlsx=='E'){
                                            wlsx='自制';
                                        }
                                        WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:wlsx});
                                    }
                                    if (!validatenull(wwhstid)){//未维护视图
                                        var sfyt = result.data.list[0].ZSFYT;
                                        if(sfyt=='1'){
                                            sfyt='';
                                        }else if(sfyt=='0'){
                                            sfyt='会计';
                                        }
                                        WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:sfyt});
                                    }
                                    if (!validatenull(wlzjid)){//物料专家
                                        sendSqlAsync("9OE35E9J3EAJE1E5EO5O13ATT5717159",result.data.list[0].ZZJD,function (data){
                                            var resJSON = JSON.parse(data.result);
                                            if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                                WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {
                                                    value:  JSON.parse(resJSON.data.body.data)[0].id,
                                                    specialobj:[
                                                        {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                                    ]
                                                });
                                            }
                                        },null,true,2880)
                                    }
                                    if (!validatenull(cgyid)){//采购员
                                        sendSqlAsync("37J911TEO91J57OJE71JTJAOJJ33AETO",result.data.list[0].EKGRP,function (data){
                                            var resJSON = JSON.parse(data.result);
                                            if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                                WfForm.changeFieldValue(cgyid+"_"+rowIndex, {
                                                    value: JSON.parse(resJSON.data.body.data)[0].id,
                                                    specialobj:[
                                                        {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                                    ]
                                                });
                                            }
                                        },null,true,2880)
                                    }

                                },function (err){
                                    msgError("查询物料信息失败！err:"+err)
                                },true);
                                if (!validatenull(djid)||!validatenull(hsdjid)){
                                    var params2 = {};
                                    params2['MATNR'] = value;
                                    var sszz = WfForm.convertFieldNameToId(config.sszz);
                                    if (validatenull(sszz)){
                                        sszz =  WfForm.convertFieldNameToId(config.sszz,"detail_"+temp);
                                        if (!validatenull(sszz)){
                                            params2['EKORG'] = getFieldValue(config.sszz,rowIndex,temp);
                                        }
                                    }else{
                                        params2['EKORG'] = getFieldValue(config.sszz);
                                    }
                                    var EKORG = params2.EKORG;
                                    if (validatenull(EKORG)){
                                        params2.EKORG = "1000" //默认是1000
                                    }
                                    params2['BUDATE'] = getDateLastYearNow();
                                    params2['EUDATE'] = getDateNow();
                                    sendGet(params2,'getsapwljg',true,function(data){
                                        var result = JSON.parse(data.result);
                                        try{
                                            WfForm.changeFieldValue(djid+"_"+rowIndex, {value:result.data.BODY[0].ITEM[0].NETPR/result.data.BODY[0].ITEM[0].PEINH});
                                            //计算含税价
                                            var hsj = (result.data.BODY[0].ITEM[0].NETPR*(1+JXSDMJSON[result.data.BODY[0].ITEM[0].EVERS]))/result.data.BODY[0].ITEM[0].PEINH
                                            WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:hsj});
                                        }catch (e){

                                        }
                                    },function (err){
                                        msgError("查询价格失败:"+err)
                                    },true,10);
                                }
                            },details[i])
                        }else{//如果有则排在后面  新的事件
                            setFieldListener(wlbmid,function (id,rowIndex,value){
                                var wlmsid = getWlms(temp);
                                var dwid = getDw(temp);
                                var djid = getWldj(temp);
                                var hsdjid = getWlhsdj(temp)
                                var wlbbid = getBb(temp);
                                var cgzid = getCgz(temp);
                                var wlzjlbid = getWlzjlb(temp);
                                var wlzjid = getWlzj(temp);
                                var cgyid = getCgy(temp);
                                var wwhstid = getWwhst(temp)
                                var wlsxid = getWlsx(temp)
                                var cgzqid = getCgzq(temp)
                                if (validatenull(value)){
                                    //清空目标字段值
                                    WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(djid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(cgyid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:null});
                                    WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:null});
                                    return;
                                }
                                let param1 = {};
                                //7.主键字段接口名=触发字段变化后的值
                                param1['MATNR'] = value;
                                param1['DATE_BEGIN'] = getDateLastYearNow();
                                param1['DATE_END'] = getDateNow();
                                param1['ClientId'] = 'com.gaoce.jt.oa';
                                param1['OperationCode'] = 'com.gaoce.jt.sap.mm001.MatnrQuery';
                                sendGet(param1,'sapwlmxsjcxsj',true,function(data){
                                    var result = JSON.parse(data.result);
                                    if (!validatenull(wlmsid)){
                                        WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:result.data.list[0].MAKTX});
                                    }
                                    if (!validatenull(dwid)){
                                        WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:result.data.list[0].MEINS});
                                    }
                                    if (!validatenull(wlbbid)){
                                        WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:result.data.list[0].ZWLBB});
                                    }
                                    if (!validatenull(wlzjlbid)){//物料专家类型
                                        WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:result.data.list[0].ZZJD});
                                    }
                                    if (!validatenull(cgzid)){//采购组
                                        WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:result.data.list[0].EKGRP});
                                    }
                                    if (!validatenull(cgzqid)){//固定采购周期
                                        WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:result.data.list[0].APLFZ});
                                    }
                                    if (!validatenull(wlsxid)){//物料属性
                                        var tscg = result.data.list[0].SOBSL;
                                        var wlsx = result.data.list[0].BESKZ;
                                        if(wlsx=='F'&&tscg=='30'){
                                            wlsx='委外';
                                        }else if(wlsx=='F'&&tscg!='30'){
                                            wlsx='外购';
                                        }else if(wlsx=='E'){
                                            wlsx='自制';
                                        }
                                        WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:wlsx});
                                    }
                                    if (!validatenull(wwhstid)){//未维护视图
                                        var sfyt = result.data.list[0].ZSFYT;
                                        if(sfyt=='1'){
                                            sfyt='';
                                        }else if(sfyt=='0'){
                                            sfyt='会计';
                                        }
                                        WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:sfyt});
                                    }
                                    if (!validatenull(wlzjid)){//物料专家
                                        sendSqlAsync("9OE35E9J3EAJE1E5EO5O13ATT5717159",result.data.list[0].ZZJD,function (data){
                                            var resJSON = JSON.parse(data.result);
                                            if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                                WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {
                                                    value:  JSON.parse(resJSON.data.body.data)[0].id,
                                                    specialobj:[
                                                        {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                                    ]
                                                });
                                            }
                                        },null,true,2880)
                                    }
                                    if (!validatenull(cgyid)){//采购员
                                        sendSqlAsync("37J911TEO91J57OJE71JTJAOJJ33AETO",result.data.list[0].EKGRP,function (data){
                                            var resJSON = JSON.parse(data.result);
                                            if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                                WfForm.changeFieldValue(cgyid+"_"+rowIndex, {
                                                    value: JSON.parse(resJSON.data.body.data)[0].id,
                                                    specialobj:[
                                                        {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                                    ]
                                                });
                                            }
                                        },null,true,2880)
                                    }

                                },function (err){
                                    msgError("查询物料信息失败！err:"+err)
                                },true);
                                if (!validatenull(djid)||!validatenull(hsdjid)){
                                    var params2 = {};
                                    params2['MATNR'] = value;
                                    var sszz = WfForm.convertFieldNameToId(config.sszz);
                                    if (validatenull(sszz)){
                                        sszz =  WfForm.convertFieldNameToId(config.sszz,"detail_"+temp);
                                        if (!validatenull(sszz)){
                                            params2['EKORG'] = getFieldValue(config.sszz,rowIndex,temp);
                                        }
                                    }else{
                                        params2['EKORG'] = getFieldValue(config.sszz);
                                    }
                                    var EKORG = params2.EKORG;
                                    if (validatenull(EKORG)){
                                        params2.EKORG = "1000" //默认是1000
                                    }
                                    params2['BUDATE'] = getDateLastYearNow();
                                    params2['EUDATE'] = getDateNow();
                                    sendGet(params2,'getsapwljg',true,function(data){
                                        var result = JSON.parse(data.result);
                                        try{
                                            WfForm.changeFieldValue(djid+"_"+rowIndex, {value:result.data.BODY[0].ITEM[0].NETPR/result.data.BODY[0].ITEM[0].PEINH});
                                            //计算含税价
                                            var hsj = (result.data.BODY[0].ITEM[0].NETPR*(1+JXSDMJSON[result.data.BODY[0].ITEM[0].EVERS]))/result.data.BODY[0].ITEM[0].PEINH
                                            WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:hsj});
                                        }catch (e){

                                        }
                                    },function (err){
                                        msgError("查询价格失败:"+err)
                                    },true,10);
                                }
                            },details[i])
                        }
                    }
                }
            }
        }
   }else{
       var details = detailNumbers.split(",");//对明细表进行分组
       for(var i=0;i<details.length;i++){
           const temp = details[i];
           if ($.isNumeric(temp)){//防止瞎写  只处理数字的
              var wlbmid =  getWlbm(temp);
              if (validatenull(wlbmid)){
                  continue;
              }else{
                  //绑定字段变动事件
                  //先查询该字段有没有绑定事件
                  var oldEvent = WfForm.__detailFieldChangeFnObj[wlbmid];
                  if (validatenull(oldEvent)){//如果没有直接执行绑定
                        setFieldListener(wlbmid,function (id,rowIndex,value){
                            var wlmsid = getWlms(temp);
                            var dwid = getDw(temp);
                            var djid = getWldj(temp);
                            var hsdjid = getWlhsdj(temp);
                            var wlbbid = getBb(temp);
                            var cgzid = getCgz(temp);
                            var wlzjlbid = getWlzjlb(temp);
                            var wlzjid = getWlzj(temp);
                            var cgyid = getCgy(temp);
                            var wwhstid = getWwhst(temp)
                            var wlsxid = getWlsx(temp)
                            var cgzqid = getCgzq(temp)
                            if (validatenull(value)){
                                //清空目标字段值
                                WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(djid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(cgyid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:null});
                                WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:null});
                                return;
                            }
                            let param1 = {};
                            //7.主键字段接口名=触发字段变化后的值
                            param1['MATNR'] = value;
                            param1['DATE_BEGIN'] = getDateLastYearNow();
                            param1['DATE_END'] = getDateNow();
                            param1['ClientId'] = 'com.gaoce.jt.oa';
                            param1['OperationCode'] = 'com.gaoce.jt.sap.mm001.MatnrQuery';
                            sendGet(param1,'sapwlmxsjcxsj',true,function(data){
                                var result = JSON.parse(data.result);
                                if (!validatenull(wlmsid)){
                                    WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:result.data.list[0].MAKTX});
                                }
                                if (!validatenull(dwid)){
                                    WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:result.data.list[0].MEINS});
                                }
                                if (!validatenull(wlbbid)){
                                    WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:result.data.list[0].ZWLBB});
                                }
                                if (!validatenull(wlzjlbid)){//物料专家类型
                                    WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:result.data.list[0].ZZJD});
                                }
                                if (!validatenull(cgzid)){//采购组
                                    WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:result.data.list[0].EKGRP});
                                }
                                if (!validatenull(cgzqid)){//固定采购周期
                                    WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:result.data.list[0].APLFZ});
                                }
                                if (!validatenull(wlsxid)){//物料属性
                                    var tscg = result.data.list[0].SOBSL;
                                    var wlsx = result.data.list[0].BESKZ;
                                    if(wlsx=='F'&&tscg=='30'){
                                        wlsx='委外';
                                    }else if(wlsx=='F'&&tscg!='30'){
                                        wlsx='外购';
                                    }else if(wlsx=='E'){
                                        wlsx='自制';
                                    }
                                    WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:wlsx});
                                }
                                if (!validatenull(wwhstid)){//未维护视图
                                    var sfyt = result.data.list[0].ZSFYT;
                                    if(sfyt=='1'){
                                        sfyt='';
                                    }else if(sfyt=='0'){
                                        sfyt='会计';
                                    }
                                    WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:sfyt});
                                }
                                if (!validatenull(wlzjid)){//物料专家
                                    sendSqlAsync("9OE35E9J3EAJE1E5EO5O13ATT5717159",result.data.list[0].ZZJD,function (data){
                                        var resJSON = JSON.parse(data.result);
                                        if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                            WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {
                                                value:  JSON.parse(resJSON.data.body.data)[0].id,
                                                specialobj:[
                                                    {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                                ]
                                            });
                                        }
                                    },null,false,2880)
                                }
                                if (!validatenull(cgyid)){//采购员
                                    sendSqlAsync("37J911TEO91J57OJE71JTJAOJJ33AETO",result.data.list[0].EKGRP,function (data){
                                        var resJSON = JSON.parse(data.result);
                                        if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                            WfForm.changeFieldValue(cgyid+"_"+rowIndex, {
                                                value: JSON.parse(resJSON.data.body.data)[0].id,
                                                specialobj:[
                                                    {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                                ]
                                            });
                                        }
                                    },null,false,2880)
                                }

                            },function (err){
                                msgError("查询物料信息失败！err:"+err)
                            },true);
                            if (!validatenull(djid)||!validatenull(hsdjid)){
                                var params2 = {};
                                params2['MATNR'] = value;
                                var sszz = WfForm.convertFieldNameToId(config.sszz);
                                if (validatenull(sszz)){
                                    sszz =  WfForm.convertFieldNameToId(config.sszz,"detail_"+temp);
                                    if (!validatenull(sszz)){
                                        params2['EKORG'] = getFieldValue(config.sszz,rowIndex,temp);
                                    }
                                }else{
                                    params2['EKORG'] = getFieldValue(config.sszz);
                                }
                                params2['BUDATE'] = getDateLastYearNow();
                                params2['EUDATE'] = getDateNow();
                                sendGet(params2,'getsapwljg',true,function(data){
                                    var result = JSON.parse(data.result);
                                    try{
                                        WfForm.changeFieldValue(djid+"_"+rowIndex, {value:result.data.BODY[0].ITEM[0].NETPR/result.data.BODY[0].ITEM[0].PEINH});
                                        //计算含税价
                                        var hsj = (result.data.BODY[0].ITEM[0].NETPR*(1+JXSDMJSON[result.data.BODY[0].ITEM[0].EVERS]))/result.data.BODY[0].ITEM[0].PEINH
                                        WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:hsj});
                                    }catch (e){

                                    }
                                },function (err){
                                    msgError("查询价格失败:"+err)
                                },true,10);
                            }
                        },details[i])
                  }else{//如果有则排在后面  新的事件
                      setFieldListener(wlbmid,function (id,rowIndex,value){
                          var wlmsid = getWlms(temp);
                          var dwid = getDw(temp);
                          var djid = getWldj(temp);
                          var hsdjid = getWlhsdj(temp);
                          var wlbbid = getBb(temp);
                          var cgzid = getCgz(temp);
                          var wlzjlbid = getWlzjlb(temp);
                          var wlzjid = getWlzj(temp);
                          var cgyid = getCgy(temp);
                          var wwhstid = getWwhst(temp)
                          var wlsxid = getWlsx(temp)
                          var cgzqid = getCgzq(temp)
                          if (validatenull(value)){
                              //清空目标字段值
                              WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(djid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(cgyid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:null});
                              WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:null});
                              return;
                          }
                          let param1 = {};
                          //7.主键字段接口名=触发字段变化后的值
                          param1['MATNR'] = value;
                          param1['DATE_BEGIN'] = getDateLastYearNow();
                          param1['DATE_END'] = getDateNow();
                          param1['ClientId'] = 'com.gaoce.jt.oa';
                          param1['OperationCode'] = 'com.gaoce.jt.sap.mm001.MatnrQuery';
                          sendGet(param1,'sapwlmxsjcxsj',true,function(data){
                              var result = JSON.parse(data.result);
                              if (!validatenull(wlmsid)){
                                  WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:result.data.list[0].MAKTX});
                              }
                              if (!validatenull(dwid)){
                                  WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:result.data.list[0].MEINS});
                              }
                              if (!validatenull(wlbbid)){
                                  WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:result.data.list[0].ZWLBB});
                              }
                              if (!validatenull(wlzjlbid)){//物料专家类型
                                  WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:result.data.list[0].ZZJD});
                              }
                              if (!validatenull(cgzid)){//采购组
                                  WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:result.data.list[0].EKGRP});
                              }
                              if (!validatenull(cgzqid)){//固定采购周期
                                  WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:result.data.list[0].APLFZ});
                              }
                              if (!validatenull(wlsxid)){//物料属性
                                  var tscg = result.data.list[0].SOBSL;
                                  var wlsx = result.data.list[0].BESKZ;
                                  if(wlsx=='F'&&tscg=='30'){
                                      wlsx='委外';
                                  }else if(wlsx=='F'&&tscg!='30'){
                                      wlsx='外购';
                                  }else if(wlsx=='E'){
                                      wlsx='自制';
                                  }
                                  WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:wlsx});
                              }
                              if (!validatenull(wwhstid)){//未维护视图
                                  var sfyt = result.data.list[0].ZSFYT;
                                  if(sfyt=='1'){
                                      sfyt='';
                                  }else if(sfyt=='0'){
                                      sfyt='会计';
                                  }
                                  WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:sfyt});
                              }
                              if (!validatenull(wlzjid)){//物料专家
                                  sendSqlAsync("9OE35E9J3EAJE1E5EO5O13ATT5717159",result.data.list[0].ZZJD,function (data){
                                      var resJSON = JSON.parse(data.result);
                                      if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                          WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {
                                              value:  JSON.parse(resJSON.data.body.data)[0].id,
                                              specialobj:[
                                                  {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                              ]
                                          });
                                      }
                                  },null,false,2880)
                              }
                              if (!validatenull(cgyid)){//采购员
                                  sendSqlAsync("37J911TEO91J57OJE71JTJAOJJ33AETO",result.data.list[0].EKGRP,function (data){
                                      var resJSON = JSON.parse(data.result);
                                      if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                          WfForm.changeFieldValue(cgyid+"_"+rowIndex, {
                                              value: JSON.parse(resJSON.data.body.data)[0].id,
                                              specialobj:[
                                                  {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                              ]
                                          });
                                      }
                                  },null,false,2880)
                              }

                          },function (err){
                              msgError("查询物料信息失败！err:"+err)
                          },true);
                          if (!validatenull(djid)||!validatenull(hsdjid)){
                              var params2 = {};
                              params2['MATNR'] = value;
                              var sszz = WfForm.convertFieldNameToId(config.sszz);
                              if (validatenull(sszz)){
                                  sszz =  WfForm.convertFieldNameToId(config.sszz,"detail_"+temp);
                                  if (!validatenull(sszz)){
                                      params2['EKORG'] = getFieldValue(config.sszz,rowIndex,temp);
                                  }
                              }else{
                                  params2['EKORG'] = getFieldValue(config.sszz);
                              }
                              params2['BUDATE'] = getDateLastYearNow();
                              params2['EUDATE'] = getDateNow();
                              sendGet(params2,'getsapwljg',true,function(data){
                                  var result = JSON.parse(data.result);
                                  try{
                                      WfForm.changeFieldValue(djid+"_"+rowIndex, {value:result.data.BODY[0].ITEM[0].NETPR/result.data.BODY[0].ITEM[0].PEINH});
                                      //计算含税价
                                      var hsj = (result.data.BODY[0].ITEM[0].NETPR*(1+JXSDMJSON[result.data.BODY[0].ITEM[0].EVERS]))/result.data.BODY[0].ITEM[0].PEINH
                                      WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:hsj});
                                  }catch (e){

                                  }
                              },function (err){
                                  msgError("查询价格失败:"+err)
                              },true,10);
                          }
                      },details[i])
                  }
              }
           }
       }
   }
}

/**
 * 一次按顺序绑定多个事件
 * @param column   要绑定的字段名 为字符串 可多个用逗号隔开
 * @param detailNumber  明细表号码
 * @param callbacks   单个方法或者方法组成的数组
 */
function setFieldListenerOrder(column,detailNumber,callbacks){
    if (callbacks instanceof Function){
        setFieldListener(column,callbacks,detailNumber)
    }else if (callbacks instanceof Array){
        for(let i=0;i<callbacks.length;i++){
            if (callbacks[i] instanceof Function){
                setFieldListener(column,callbacks[i],detailNumber)
            }
        }
    }
}
//**********************************Ajax end**********************************************//
//**********************************自定义业务逻辑start*******************************************//

/**
 * 采购合同创建
 */

function createCustomValues(){
    var htfl = getFieldValue("sys_autogen_cm_mouldtype");
    var deparemtcode = ""
    var fieldVal3 = "";
    if (["6","7","8"].includes(htfl)){
        deparemtcode = getFieldValue('fybmhlybm','0',3);
        var xmh = getFieldValue('xmh','0',3);
        var xmjd = getFieldValue('jd','0',3);
        if (xmh === '00000'){
            fieldVal3 = "00000";
        }else {
            fieldVal3 = xmjd;
        }
    }else{
        deparemtcode = getFieldValue('fybmhlybm','0',1);
        var xmh = getFieldValue('zcxmh','0',1);
        var xmjd = getFieldValue('zcxmjd','0',1);
        if (xmh === '00000'){
            fieldVal3 = "00000";
        }else {
            fieldVal3 = xmjd;
        }
    }
    var yslx = getFieldValue('yslx');
    var fieldCode2 = "";
    var fieldVal2 = "";
    if (yslx==="2"){
        fieldCode2 = "raiseInvestment1";
    }else{
        fieldCode2 = "whetherToDevelop";
    }
    if (yslx==='1'||yslx==='3'){
        fieldVal2 = "YF"
    }else if (yslx==='0'){
        fieldVal2 = "FYF"
    }else{
        fieldVal2 = "false"
    }
    var customValues = [
        {
            "fieldCode": "department",
            "value": deparemtcode
        },
        {
            "fieldCode": fieldCode2,
            "value": fieldVal2
        },
        {
            "fieldCode": "projectNumber",
            "value": fieldVal3
        }
    ]
    return customValues;
}
function createContractlines(){
    const rows = getRowIndexStr(2);
    const res = [];
    for(let i=0; i<rows.length; i++){
        let templete = {
            "stageCode": getFieldValue('fktjbh',rows[i],2),
            "stageName": getShowNameOA('fktj',rows[i],2),
            "partnerCategory": "VENDOR",
            "partnerCode": getFieldValue('gys'),
            "amount": validatenull(getFieldValue('fkje',rows[i],2))?0:parseFloat(getFieldValue('fkje',rows[i],2)),
            "stagePaidPaymentAmount": null,
            "stagePaidAdvancesAmount": null,
            "partnerBankAccountNo": null,
            "paymentConditions": getShowNameOA('fkfs',rows[i],2),
            "settlementMethod": "FixedAmount",
            "price": validatenull(getFieldValue('fkje',rows[i],2))?0:parseFloat(getFieldValue('fkje',rows[i],2)),
            "dueDate": null,
            "whetherReceiptInvoice": getFieldValue('kpjd',rows[i],2)==='0',
            "remark": null
        };
        res.push(templete);
    }
    return res;
}
function createContractSubjectMatterLines(){
    var yslx = getFieldValue('yslx');
    var projectVal = "";
    if (yslx==="2"){
        projectVal = "PROJECT";
    }else{
        projectVal = "PROJECT2";
    }
    var res = [];
    var fyxmh = 'fyxmbh'
    var number = 1;
    var htfl = getFieldValue("sys_autogen_cm_mouldtype");
    if (["6","7","8"].includes(htfl)){
        number = 3;
        fyxmh = 'fyxmh'
    }
    var rows = getRowIndexStr(number);
    for(let i=0;i<rows.length;i++){
        var templete = {
            //"id": null,
            //"deleteFlag": null,
            "expenseTypeCode": getShowNameOA(fyxmh,rows[i],number),
            "lineCustomFormValues": [],
            "contractApportionmentDTOList": []
        }
        var lineCustomFormValues = [];
        var linetemp = {
            "fieldCode": "LineAmount",
            "value": number === 3?getFieldValue('zxje',rows[i],number):getFieldValue('jshj',rows[i],number)
            //"value": getFieldValue('htje')
        }
        lineCustomFormValues.push(linetemp)
        templete["lineCustomFormValues"] = lineCustomFormValues;

        var contractApportionmentDTOList = [];
        var deparemtcode = "";
        var fieldVal3 = "";
        if (["6","7","8"].includes(htfl)){
            deparemtcode = getFieldValue('fybmhlybm','0',3);
            var xmh = getFieldValue('xmh','0',3);
            var xmjd = getFieldValue('jd','0',3);
            if (xmh === '00000'){
                fieldVal3 = "00000";
            }else {
                fieldVal3 = xmjd;
            }
        }else{
            deparemtcode = getFieldValue('fybmhlybm','0',1);
            var xmh = getFieldValue('zcxmh','0',1);
            var xmjd = getFieldValue('zcxmjd','0',1);
            if (xmh === '00000'){
                fieldVal3 = "00000";
            }else {
                fieldVal3 = xmjd;
            }
        }
        var contractTemp = {
            "amount": number === 3?getFieldValue('zxje',rows[i],number):getFieldValue('jshj',rows[i],number),
            "openApportionViewRequestDTOList": [{
                "fieldType": "department",
                "costCenterItemCode": deparemtcode
            },
                {
                    "fieldType": "costCenter",
                    "costCenterCode": projectVal,
                    "costCenterItemCode": fieldVal3
                }
            ]
        }
        contractApportionmentDTOList.push(contractTemp)
        templete.contractApportionmentDTOList = contractApportionmentDTOList;
        res.push(templete);
    }
    return res;
}

/**
 * 合同创建方法
 * @returns {any}
 */
function contractCreate(){
    var yslx = getFieldValue('yslx');
    var contractTypeCode = "";
    if (yslx==="2"){
        contractTypeCode = "capitalFixedAmountContracts";
    }else{
        contractTypeCode = "NocapitalFixedAmountContracts";
    }
    var bzz = getFieldValue('bz');
    if(!validatenull(bzz)&&bzz.length>100){
        bzz = bzz.slice(0,100) + "...(详情见OA原单据)";//备注过长传汇联易会报错
    }
    var bb = getFieldValue('bb');
    if(bb == 0){
        bb = 'CNY'
    }else if(bb == 2){
        bb = 'SGD'
    }else if(bb == 3){
        bb = 'USD'
    }
    var params = {
        "contractHead": {
            "applicantEmployeeId": getFieldValue('fqrgh'), //发起人工号 固定取表单字段fqrgh
            "setOfBooksCode": "DEFAULT_SOB",
            "contractCategory": "CONTRACT",
            "contractTypeCode": contractTypeCode,//合同类别
            "partnerCategory": "VENDOR",
            "partnerCode": getFieldValue('gys'),//供应商编码
            "refContractNumber": null,
            // "currencyCode": getFieldValue("sczznew")=='7000'?"USD":"CNY",//新加坡公司7000
            "currencyCode": bb,//币别
            "contractNumber": getFieldValue("htbh"),//合同编号
            "originContractNumber": null,
            "companyCode": getFieldValue("sczznew"),
            "contractName": getFieldValue("htmc"),//合同名称
            "signDate": null,
            "amount": getFieldValue('htje'),//合同金额
            "remark": bzz,//备注
            "liableCustDeptNum": null,
            "liableCustDeptNumList": null,
            "liablePersonEmployeeId": getFieldValue('zxcggh'),//执行采购工号
            "startDate": null,
            "endDate": null,
            "status": null,
            "customFormValues": createCustomValues()
        },
        "contractLines": createContractlines(),
        "contractSubjectMatterLines": createContractSubjectMatterLines()
    }
    return sendPost(params,'HELIOS006');
}


/**
 * 采购合同变更
 */

function createCustomValuesChange(){
    var htfl = getFieldValue("sys_autogen_cm_mouldtype");
    var deparemtcode = ""
    var fieldVal3 = "";
    if (["6","7","8"].includes(htfl)){
        deparemtcode = getFieldValue('fybmbmsap','0',3);
        var xmh = getFieldValue('xmh','0',3);
        var xmjd = getFieldValue('jd','0',3);
        if (xmh === '00000'){
            fieldVal3 = "00000";
        }else {
            fieldVal3 = xmjd;
        }
    }else{
        deparemtcode = getFieldValue('fybmbmsap','0',1);
        var xmh = getFieldValue('xmh','0',1);
        var xmjd = getFieldValue('xmjd','0',1);
        if (xmh === '00000'){
            fieldVal3 = "00000";
        }else {
            fieldVal3 = xmjd;
        }
    }
    var yslx = getFieldValue('yslx');
    var fieldCode2 = "";
    var fieldVal2 = "";
    if (yslx==="2"){
        fieldCode2 = "raiseInvestment1";
    }else{
        fieldCode2 = "whetherToDevelop";
    }
    if (yslx==='1'||yslx==='3'){
        fieldVal2 = "YF"
    }else if (yslx==='0'){
        fieldVal2 = "FYF"
    }else{
        fieldVal2 = false
    }
    var customValues = [
        {
            "fieldCode": "department",
            "value": deparemtcode
        },
        {
            "fieldCode": fieldCode2,
            "value": fieldVal2
        },
        {
            "fieldCode": "projectNumber",
            "value": fieldVal3
        }
    ]
    return customValues;
}
function createContractlinesChange(){
    const rows = getRowIndexStr(2);
    const res = [];
    for(let i=0; i<rows.length; i++){
        let templete = {
            "stageCode": getFieldValue('fktjbm',rows[i],2),
            "stageName": getShowNameOA('fktj',rows[i],2),
            "partnerCategory": "VENDOR",
            "partnerCode": getFieldValue('gys'),
            "amount": validatenull(getFieldValue('fkje',rows[i],2))?0:parseFloat(getFieldValue('fkje',rows[i],2)),
            "stagePaidPaymentAmount": null,
            "stagePaidAdvancesAmount": null,
            "partnerBankAccountNo": null,
            "paymentConditions": getShowNameOA('fkfs',rows[i],2),
            "settlementMethod": "FixedAmount",
            "price": validatenull(getFieldValue('fkje',rows[i],2))?0:parseFloat(getFieldValue('fkje',rows[i],2)),
            "dueDate": null,
            "whetherReceiptInvoice": getFieldValue('kpjd',rows[i],2)==='0',
            "remark": null
        };
        res.push(templete);
    }
    return res;
}
function createContractSubjectMatterLinesChange(){
    var yslx = getFieldValue('yslx');
    var projectVal = "";
    if (yslx==="2"){
        projectVal = "PROJECT";
    }else{
        projectVal = "PROJECT2";
    }
    var res = [];
    var fyxmh = 'fyxmbh'
    var number = 1;
    var htfl = getFieldValue("sys_autogen_cm_mouldtype");
    if (["6","7","8"].includes(htfl)){
        number = 3;
        fyxmh = 'fyxmh'
    }
    var rows = getRowIndexStr(number);
    for(let i=0;i<rows.length;i++){
        var templete = {
            "id": getFieldValue('htid'),
            "deleteFlag": "False",
            "expenseTypeCode": getShowNameOA(fyxmh,rows[i],number),
            "lineCustomFormValues": [],
            "contractApportionmentDTOList": []
        }
        var lineCustomFormValues = [];
        var linetemp = {
            "fieldCode": "LineAmount",
            "value": number === 3?getFieldValue('zxje',rows[i],number):getFieldValue('jshj',rows[i],number)
        }
        lineCustomFormValues.push(linetemp)
        templete["lineCustomFormValues"] = lineCustomFormValues;

        var contractApportionmentDTOList = [];
        var deparemtcode = "";
        var fieldVal3 = "";
        if (["6","7","8"].includes(htfl)){
            deparemtcode = getFieldValue('fybmbmsap','0',3);
            var xmh = getFieldValue('xmh','0',3);
            var xmjd = getFieldValue('jd','0',3);
            if (xmh === '00000'){
                fieldVal3 = "00000";
            }else {
                fieldVal3 = xmjd;
            }
        }else{
            deparemtcode = getFieldValue('fybmbmsap','0',1);
            var xmh = getFieldValue('xmh','0',1);
            var xmjd = getFieldValue('xmjd','0',1);
            if (xmh === '00000'){
                fieldVal3 = "00000";
            }else {
                fieldVal3 = xmjd;
            }
        }
        var contractTemp = {
            "amount": number === 3?getFieldValue('zxje',rows[i],number):getFieldValue('jshj',rows[i],number),
            "openApportionViewRequestDTOList": [{
                "fieldType": "department",
                "costCenterItemCode": deparemtcode,
                "costCenterCode":null
            },
                {
                    "fieldType": "costCenter",
                    "costCenterCode": projectVal,
                    "costCenterItemCode": fieldVal3
                }
            ]
        }
        contractApportionmentDTOList.push(contractTemp)
        templete.contractApportionmentDTOList = contractApportionmentDTOList;
        res.push(templete);
    }
    return res;
}
function contractChange(){
    var params = {
        "contractHead": {
            //"applicantEmployeeId": getFieldValue('fqrgh'), //发起人工号 固定取表单字段fqrgh
            "setOfBooksCode": "DEFAULT_SOB",
            "contractCategory": "CONTRACT",
            "partnerCategory": "VENDOR",
            "partnerCode": getFieldValue('gys'),//供应商编码
            "refContractNumber": null,
            "currencyCode": "CNY",
            "contractNumber": getShowNameOA("htbh"),//合同编号
            "originContractNumber": null,
            "companyCode": getFieldValue("sczznew"),
            "contractName": getFieldValue("htmc"),//合同名称
            "signDate": null,
            "amount": getFieldValue('bghhtje'),//合同金额
            "remark": getFieldValue('bz'),//备注
            "liableCustDeptNum": null,
            "liableCustDeptNumList": null,
            "liablePersonEmployeeId": getFieldValue('dqspr'),//执行采购工号
            "startDate": null,
            "endDate": null,
            "status": getFieldValue("spzt"),//审批状态
            "customFormValues": createCustomValuesChange()
        },
        "contractLines": createContractlinesChange(),
        "contractSubjectMatterLines": createContractSubjectMatterLinesChange()
    }
    return sendPost(params,'HELIOS007');
}


/*var reqJson = {
    groupXmh:"", //组号
    group:"",   //组
    yfxmh:"",   //研发项目号
    mappingid:"", //映射字段名称或id  非必填
    rowIndex:"",  //明细行号  用于映射字段  非必填
    sczznew:"", //申请组织号码  非必填 默认取sczznew的值
    async:true,  //是否异步 非必填 默认异步
    success:function (res){ //非必填  成功回调
        //dosth...
    },
    eventKey:'ysyecx' //默认 ysyecx 非必填
}*/
/**
 * 调用获取预算余额接口
 * @param fybm
 * @param yfxmh
 * @param mappingId  需要映射字段的名称
 * @param callback
 * @param group
 * @param sczznew
 */
function getBudgetBalanceMain(fybm,yfxmh,mappingId,callback,group,sczznew){
    if (validatenull(group)){
        group = "BUDGET_ITEM";
    }
    if (validatenull(sczznew)){
        sczznew = getFieldValue('sczznew')
    }
    var twoYearsAndElevenMonthsAgo = new Date();
    twoYearsAndElevenMonthsAgo.setFullYear(twoYearsAndElevenMonthsAgo.getFullYear() - 2);
    var timestampYYYY = twoYearsAndElevenMonthsAgo.getFullYear();
    var timestampYYYYMM = twoYearsAndElevenMonthsAgo.toISOString().substring(0, 7);
    var params = {
        "companyCode":sczznew,
        "organizationCode":"gaoce001",
        "scenarioCode":"999",
        "versionCode":"999",
        "structureCode":"2",
        "periodSummaryFlag":true,
        "amountQuarterFlag":"AMOUNT",
        "yearLimit":null,
        "yearLowerLimit":timestampYYYY,
        "yearUpperLimit":dateformat(new Date(),"yyyy"),
        "semiannualLimit":"",
        "quarterLowerLimit":null,
        "quarterUpperLimit":null,
        "periodLowerLimit":timestampYYYYMM,
        "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
        "filterDisableFlag":null,
        "page":0,
        "size":10
    }
    var queryLineList = [];
    var item1 =  {
        "parameterType":"BGT_RULE_PARAMETER_BUDGET",
        "parameterCode":group,
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode": fybm
            }
        ]
    }
    var item2 = {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT3",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":"YF"
            }
        ]
    }
    var item3 =  {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT2",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":yfxmh
            }
        ]
    }
    queryLineList.push(item1);
    queryLineList.push(item2);
    queryLineList.push(item3);
    params["queryLineList"] = queryLineList;
    if (validatenull(callback)){
        var res  = sendGet(params,"ysyecx");
        setFieldValueOA(mappingId,res.data.data.queryResultList[0].expAvailableAmount)
    }else{
        sendGet(params,"ysyecx",true ,callback)
    }
}

/**
 * 获取资本性预算余额主表
 * @param budgetItem
 * @param fyxmbm
 * @param xmbm
 * @param mappingId
 * @param callback
 * @param sczznew
 */
function getBudgetBalanceMainZBX(budgetItem,fyxmbm,xmbm,mappingId,callback,sczznew){
    if (validatenull(sczznew)){
        sczznew = getFieldValue('sczznew')
    }
    var twoYearsAndElevenMonthsAgo = new Date();
        twoYearsAndElevenMonthsAgo.setFullYear(twoYearsAndElevenMonthsAgo.getFullYear() - 2);
    var timestampYYYY = twoYearsAndElevenMonthsAgo.getFullYear();
    var timestampYYYYMM = twoYearsAndElevenMonthsAgo.toISOString().substring(0, 7);
    var params = {
        "companyCode":sczznew,
        "organizationCode":"gaoce001",
        "scenarioCode":"999",
        "versionCode":"999",
        "structureCode":"1",
        "periodSummaryFlag":true,
        "amountQuarterFlag":"AMOUNT",
        "yearLimit":null,
        "yearLowerLimit":timestampYYYY,
        "yearUpperLimit":dateformat(new Date(),"yyyy"),
        "semiannualLimit":"",
        "quarterLowerLimit":null,
        "quarterUpperLimit":null,
        "periodLowerLimit":timestampYYYYMM,
        "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
        "filterDisableFlag":null,
        "page":0,
        "size":10
    }
    var queryLineList = [];
    var item1 =  {
        "parameterType":"BGT_RULE_PARAMETER_BUDGET",
        "parameterCode":budgetItem,
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode": fyxmbm
            }
        ]
    }
    var item2 = {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":xmbm+"-01"
            }
        ]
    }
    queryLineList.push(item1);
    queryLineList.push(item2);
    params["queryLineList"] = queryLineList;
    if (validatenull(callback)){
        var res  = sendGet(params,"ysyecx");
        setFieldValueOA(mappingId,res.data.data.queryResultList[0].expAvailableAmount)
    }else{
        sendGet(params,"ysyecx",true ,callback)
    }
}

/**
 * 部门预算查询
 * @param budgetItem
 * @param fyxmbm  费用项目编码
 * @param fybmbm  费用部门编码
 * @param mappingId   映射字段名称
 * @param callback  回调
 * @param sczznew   申请组织代码默认取“sczznew”的值
 */
function getBudgetBalanceMainDept(budgetItem,fyxmbm,fybmbm,mappingId,callback,sczznew){
    if (validatenull(sczznew)){
        sczznew = getFieldValue('sczznew')
    }
    var params = {
        "companyCode":sczznew,
        "organizationCode":"gaoce001",
        "structureCode":"BM01",
        "scenarioCode":"999",
        "versionCode":"999",
        "periodSummaryFlag":true,
        "amountQuarterFlag":"AMOUNT",
        "yearLimit":dateformat(new Date(),"yyyy"),
        "yearLowerLimit":dateformat(new Date(),"yyyy"),
        "yearUpperLimit":dateformat(new Date(),"yyyy"),
        "periodLowerLimit":dateformat(new Date(),"yyyy")+"-01",
        "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
        "filterDisableFlag":null,
        "page":0,
        "size":10
    }
    var queryLineList = [];
    var item1 =  {
        "parameterType":"BGT_RULE_PARAMETER_BUDGET",
        "parameterCode":budgetItem,
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode": fyxmbm
            }
        ]
    }
    var item2 = {
        "parameterType":"BGT_RULE_PARAMETER_ORG",
        "parameterCode":"UNIT_GROUP",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":fybmbm
            }
        ]
    }
    var item3 = {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT3",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":"FYF"
            }
        ]
    }
    queryLineList.push(item1);
    queryLineList.push(item2);
    queryLineList.push(item3);
    params["queryLineList"] = queryLineList;
    if (validatenull(callback)){
        var res  = sendGet(params,"ysyecx");
        setFieldValueOA(mappingId,res.data.data.queryResultList[0].expAvailableAmount)
    }else{
        sendGet(params,"ysyecx",true ,callback)
    }
}

/**
 * 调用获取预算余额接口明细表   研发
 * @param reqJson
 * @returns {any}
 */
function getBudgetBalance(reqJson){
    var target = {
        groupXmh:"",
        group:"",
        yfxmh:"",
        mappingid:"",
        rowIndex:"",
        sczznew:"",
        async:true,
        success:function (res){
            const result = JSON.parse(res.result);
            if(result.data.hasOwnProperty("data")){
                setFieldValueOA(reqJson.mappingid,result.data.data.queryResultList[0].expAvailableAmount,reqJson.rowIndex)
            }else{
                //这里暂定不赋值吧
                //setFieldValueOA(reqJson.mappingid,0,reqJson.rowIndex)
            }
        },
        eventKey:'ysyecx'
    }
    reqJson = smartMerge(reqJson,target);
    if (validatenull(reqJson.sczznew)){
        reqJson.sczznew = getFieldValue('sczznew')
    }
    if (validatenull(reqJson.group)){
        reqJson.group = "BUDGET_ITEM";
    }
    var twoYearsAndElevenMonthsAgo = new Date();
        twoYearsAndElevenMonthsAgo.setFullYear(twoYearsAndElevenMonthsAgo.getFullYear() - 2);


    var timestampYYYY = twoYearsAndElevenMonthsAgo.getFullYear();
    var timestampYYYYMM = twoYearsAndElevenMonthsAgo.toISOString().substring(0, 7);
    var params = {
        "companyCode":reqJson.sczznew,
        "organizationCode":"gaoce001",
        "scenarioCode":"999",
        "versionCode":"999",
        "structureCode":"2",
        "periodSummaryFlag":true,
        "amountQuarterFlag":"AMOUNT",
        "yearLimit":null,
        "yearLowerLimit":timestampYYYY,
        "yearUpperLimit":dateformat(new Date(),"yyyy"),
        "semiannualLimit":"",
        "quarterLowerLimit":null,
        "quarterUpperLimit":null,
        "periodLowerLimit":timestampYYYYMM,
        "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
        "filterDisableFlag":null,
        "page":0,
        "size":10
    }
    var queryLineList = [];
    var item1 =  {
        "parameterType":"BGT_RULE_PARAMETER_BUDGET",
        "parameterCode":reqJson.group,
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode": reqJson.groupXmh
            }
        ]
    }
    var item2 = {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT3",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":"YF"
            }
        ]
    }
    var item3 =  {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT2",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":reqJson.yfxmh
            }
        ]
    }
    queryLineList.push(item1);
    queryLineList.push(item2);
    queryLineList.push(item3);
    params["queryLineList"] = queryLineList;
    if (reqJson.async){
        sendGet(params,reqJson.eventKey,reqJson.async ,reqJson.success);
    }else{
        return sendGet(params,reqJson.eventKey);
    }
}

/**
 * 调用获取预算余额接口明细表  部门-研发-资本  根据预算类型动态查询预算余额
 * @param yslx   预算类型  0 部门 1或3 研发 2 资本
 * @param yfxmh   研发项目号 或带阶段
 * @param fyxmbm  费用项目编码
 * @param fyxmbm  费用部门编码
 * @param mappingid  需要映射字段的id
 * @param sczznew  组织编码
 * @returns {any}
 */
function getBudgetBalanceDynamic(yslx,yfxmh,fyxmbm,fybmbm,mappingid,rowIndex,sczznew){
    if (validatenull(sczznew)){
        sczznew = getFieldValue('sczznew')
    }
    var params = {};
    var queryLineList = [];
    var twoYearsAndElevenMonthsAgo = new Date();
        twoYearsAndElevenMonthsAgo.setFullYear(twoYearsAndElevenMonthsAgo.getFullYear() - 2);


    var timestampYYYY = twoYearsAndElevenMonthsAgo.getFullYear();
    var timestampYYYYMM = twoYearsAndElevenMonthsAgo.toISOString().substring(0, 7);
    if (yslx=="1"||yslx=="3"){
         params = {
            "companyCode":sczznew,
            "organizationCode":"gaoce001",
            "scenarioCode":"999",
            "versionCode":"999",
            "structureCode":"2",
            "periodSummaryFlag":true,
            "amountQuarterFlag":"AMOUNT",
            "yearLimit":null,
            "yearLowerLimit":timestampYYYY,
            "yearUpperLimit":dateformat(new Date(),"yyyy"),
            "semiannualLimit":"",
            "quarterLowerLimit":null,
            "quarterUpperLimit":null,
            "periodLowerLimit":timestampYYYYMM,
            "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
            "filterDisableFlag":null,
            "page":0,
            "size":10
        }
        var item1 =  {
            "parameterType":"BGT_RULE_PARAMETER_BUDGET",
            "parameterCode":"BUDGET_ITEM",
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode": fyxmbm  //费用项目编码
                }
            ]
        }
        var item2 = {
            "parameterType":"BGT_RULE_PARAMETER_DIM",
            "parameterCode":'PROJECT3',
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode":'YF'
                }
            ]
        }
        var item3 =  {
            "parameterType":"BGT_RULE_PARAMETER_DIM",
            "parameterCode":'PROJECT2',
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode":yfxmh
                }
            ]
        }
        queryLineList.push(item1);
        queryLineList.push(item2);
        queryLineList.push(item3);
    }else if(yslx=="0"){
        params = {
            "companyCode":sczznew,
            "organizationCode":"gaoce001",
            "structureCode":"BM01",
            "scenarioCode":"999",
            "versionCode":"999",
            "periodSummaryFlag":true,
            "amountQuarterFlag":"AMOUNT",
            "yearLimit":dateformat(new Date(),"yyyy"),
            "yearLowerLimit":dateformat(new Date(),"yyyy"),
            "yearUpperLimit":dateformat(new Date(),"yyyy"),
            "periodLowerLimit":dateformat(new Date(),"yyyy")+"-01",
            "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
            "filterDisableFlag":null,
            "page":0,
            "size":10
        }
        var item1 =  {
            "parameterType":"BGT_RULE_PARAMETER_BUDGET",
            "parameterCode":"BUDGET_ITEM",
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode": fyxmbm  //费用项目编码
                }
            ]
        }
        var item2 = {
            "parameterType":"BGT_RULE_PARAMETER_ORG",
            "parameterCode":'UNIT_GROUP',
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode":fybmbm
                }
            ]
        }
        var item3 =  {
            "parameterType":"BGT_RULE_PARAMETER_DIM",
            "parameterCode":'PROJECT3',
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode":'FYF'
                }
            ]
        }
        queryLineList.push(item1);
        queryLineList.push(item2);
        queryLineList.push(item3);
    }else if(yslx=="2"){
        params = {
            "companyCode":sczznew,
            "organizationCode":"gaoce001",
            "scenarioCode":"999",
            "versionCode":"999",
            "structureCode":"1",
            "periodSummaryFlag":true,
            "amountQuarterFlag":"AMOUNT",
            "yearLimit":null,
            "yearLowerLimit":timestampYYYY,
            "yearUpperLimit":dateformat(new Date(),"yyyy"),
            "semiannualLimit":"",
            "quarterLowerLimit":null,
            "quarterUpperLimit":null,
            "periodLowerLimit":timestampYYYYMM,
            "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
            "filterDisableFlag":null,
            "page":0,
            "size":10
        }
        var item1 =  {
            "parameterType":"BGT_RULE_PARAMETER_BUDGET",
            "parameterCode":"BUDGET_ITEM",
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode": fyxmbm  //费用项目编码
                }
            ]
        }
        var item2 = {
            "parameterType":"BGT_RULE_PARAMETER_DIM",
            "parameterCode":'PROJECT',
            "isAll":false,
            "queryParameterList":[
                {
                    "parameterValueCode":yfxmh+'-01'
                }
            ]
        }
        queryLineList.push(item1);
        queryLineList.push(item2);
    }
    params["queryLineList"] = queryLineList;
    sendGet(params,'ysyecx',true ,function (res){
        const result = JSON.parse(res.result);
        setFieldValueOA(mappingid,result.data.data.queryResultList[0].expAvailableAmount,rowIndex)
    });
}


/**
 * 调用获取预算余额接口明细表   资本性
 * @param budgetItem
 * @param fyxmbm
 * @param xmbm
 * @param mappingid
 * @param rowIndex
 * @param sczznew
 */
function getBudgetBalanceZBX(budgetItem,fyxmbm,xmbm,mappingid,rowIndex,sczznew){
    if(budgetItem===""||budgetItem===null||budgetItem===undefined){
        return;
    }
        var success  =function (res){
            const result = JSON.parse(res.result);
            setFieldValueOA(mappingid,result.data.data.queryResultList[0].expAvailableAmount,rowIndex)
        }
    if (validatenull(sczznew)){
        sczznew = getFieldValue('sczznew')
    }
    var twoYearsAndElevenMonthsAgo = new Date();
        twoYearsAndElevenMonthsAgo.setFullYear(twoYearsAndElevenMonthsAgo.getFullYear() - 2);


    var timestampYYYY = twoYearsAndElevenMonthsAgo.getFullYear();
    var timestampYYYYMM = twoYearsAndElevenMonthsAgo.toISOString().substring(0, 7);
    var params = {
        "companyCode":sczznew,
        "organizationCode":"gaoce001",
        "scenarioCode":"999",
        "versionCode":"999",
        "structureCode":"1",
        "periodSummaryFlag":true,
        "amountQuarterFlag":"AMOUNT",
        "yearLimit":null,
        "yearLowerLimit":timestampYYYY,
        "yearUpperLimit":dateformat(new Date(),"yyyy"),
        "semiannualLimit":"",
        "quarterLowerLimit":null,
        "quarterUpperLimit":null,
        "periodLowerLimit":timestampYYYYMM,
        "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
        "filterDisableFlag":null,
        "page":0,
        "size":10
    }
    var queryLineList = [];
    var item1 =  {
        "parameterType":"BGT_RULE_PARAMETER_BUDGET",
        "parameterCode":budgetItem,
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode": fyxmbm
            }
        ]
    }
    var item2 = {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":xmbm+"-01"
            }
        ]
    }
    queryLineList.push(item1);
    queryLineList.push(item2);
    params["queryLineList"] = queryLineList;
    sendGet(params,'ysyecx',true ,success);
}

/**
 * 调用获取预算余额接口明细表   自动化
 * @param reqJson
 * @returns {any}
 */
function getBudgetBalanceZDH(reqJson){
    var target = {
        groupXmh:"",
        group:"",
        yfxmh:"",
        mappingid:"",
        rowIndex:"",
        sczznew:"",
        async:true,
        success:function (res){
            const result = JSON.parse(res.result);
            setFieldValueOA(reqJson.mappingid,result.data.data.queryResultList[0].expAvailableAmount,reqJson.rowIndex)
        },
        eventKey:'ysyecx'
    }
    reqJson = smartMerge(reqJson,target);
    if (validatenull(reqJson.sczznew)){
        reqJson.sczznew = getFieldValue('sczznew')
    }
    if (validatenull(reqJson.group)){
        reqJson.group = "BUDGET_ITEM";
    }
    var twoYearsAndElevenMonthsAgo = new Date();
    twoYearsAndElevenMonthsAgo.setFullYear(twoYearsAndElevenMonthsAgo.getFullYear() - 2);
    var timestampYYYY = twoYearsAndElevenMonthsAgo.getFullYear();
    var timestampYYYYMM = twoYearsAndElevenMonthsAgo.toISOString().substring(0, 7);
    var params = {
        "companyCode":reqJson.sczznew,
        "organizationCode":"gaoce001",
        "scenarioCode":"999",
        "versionCode":"999",
        "structureCode":"ZDH",
        "periodSummaryFlag":true,
        "amountQuarterFlag":"AMOUNT",
        "yearLimit":null,
        "yearLowerLimit":timestampYYYY,
        "yearUpperLimit":dateformat(new Date(),"yyyy"),
        "semiannualLimit":"",
        "quarterLowerLimit":null,
        "quarterUpperLimit":null,
        "periodLowerLimit":timestampYYYYMM,
        "periodUpperLimit":dateformat(new Date(),"yyyy-MM"),
        "filterDisableFlag":null,
        "page":0,
        "size":10
    }
    var queryLineList = [];
    var item1 =  {
        "parameterType":"BGT_RULE_PARAMETER_BUDGET",
        "parameterCode":reqJson.group,
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode": reqJson.groupXmh
            }
        ]
    }
    var item2 = {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT3",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":"ZDH"
            }
        ]
    }
    var item3 =  {
        "parameterType":"BGT_RULE_PARAMETER_DIM",
        "parameterCode":"PROJECT2",
        "isAll":false,
        "queryParameterList":[
            {
                "parameterValueCode":reqJson.yfxmh
            }
        ]
    }
    queryLineList.push(item1);
    queryLineList.push(item2);
    queryLineList.push(item3);
    params["queryLineList"] = queryLineList;
    if (reqJson.async){
        sendGet(params,reqJson.eventKey,reqJson.async ,reqJson.success);
    }else{
        return sendGet(params,reqJson.eventKey);
    }
}

/**
 * 判断多个明细表中指定字段是否有相同值的明细行
 * @param detailNumbers  如“1,2” 表示明细表1和2
 * @param cols   如“fyxm”或“fyxm,fyxm” 或“fyxm,sm”  如果cols只有一个值则意味着取明细表的字段均为该名称字段  如果明细表字段名称不同请用”,“进行隔开
 * @returns {boolean}  true或者false   true标识存在相同字段值的明细行
 */
function checkDetailFieldVal(detailNumbers,cols){
    var arr_detail = detailNumbers.split(",");
    var arr_col = cols.split(",");
    if (!contains(cols,",")){
        arr_col = [];
        arr_detail.forEach(i=>{
            arr_col.push(cols);
        })
    }
    var arr_arr_detail = [];
    for (var i=0;i<arr_detail.length;i++){
        var item = [];
        var rows  = getRowIndexStr(arr_detail[i]);
        for(var j=0;j<rows.length;j++){
            if (!validatenull(getFieldValue(arr_col[i],rows[j],arr_detail[i]))){
                item.push(getFieldValue(arr_col[i],rows[j],arr_detail[i]));
            }
        }
        arr_arr_detail.push(item);
    }
    var start = 0;
    for(var j=0;j<arr_arr_detail.length-1;j++){
        var k=1;
        while (k<=arr_arr_detail.length-1){
            if (check2ArrHasSameEle(arr_arr_detail[j],arr_arr_detail[k])){
                return true;
            }else{
                k+=1;
            }
        }
        start+=1;
    }
    return false;
}

/**
 * 校验明细表是否存在相同明细行  可以指定字段 按照字段来判断是否算作是相同明细行  如果不传cols  则默认标识所有字段值均相同才算相同明细行  cols可传多个用","隔开
 * @param detailNumber 明细表号码
 * @param cols  字段（可多个,","隔开）
 */
function  checkDetailExistSameRow(detailNumber,cols){
    if (validatenull(detailNumber)){
        msgBox("请指定明细表");
        return;
    }
    var tabledata = getRowsDataOA(detailNumber);
    var checkedRows = [];
    var result = false;
    if (validatenull(cols)){
        for(var i=0;i<tabledata.length;i++){
            var rowData = tabledata[i];
            for(var j=0;j<checkedRows.length;j++){
                if (JSON.stringify(rowData) === JSON.stringify(checkedRows[j])) {
                    result =  true;
                    break;
                }
            }
            checkedRows.push(rowData);
        }
    }else{
        var colData = [];
        var colarr = cols.split(",");
        for(var i=0;i<tabledata.length;i++){
            var obj = {};
            for(var j=0;j<colarr.length;j++){
                obj[colarr[j]] = tabledata[i][colarr[j]];
            }
            colData.push(obj);
        }
        for(var i=0;i<colData.length;i++){
            var rowData = colData[i];
            for(var j=0;j<checkedRows.length;j++){
                if (JSON.stringify(rowData) === JSON.stringify(checkedRows[j])) {
                    result =  true;
                    console.log('第'+(i+1)+','+(j+1)+'行数据重复!')
                    break;
                }
            }
            checkedRows.push(rowData);
        }
    }
    return result;
}


/**
 * 校验明细表是否存在相同明细行  可以指定字段 按照字段来判断是否算作是相同明细行  如果不传cols  则默认标识所有字段值均相同才算相同明细行  cols可传多个用","隔开
 * @param detailNumber 明细表号码
 * @param cols  字段（可多个,","隔开）
 * @param indexs 行标识数组  意思为只校验这些行
 */
function  checkDetailExistSameRowExcludes(detailNumber,cols,indexs){
    if (validatenull(detailNumber)){
        msgBox("请指定明细表");
        return;
    }
    var tabledata = getRowsDataOAWithIndexs(detailNumber,indexs);
    var checkedRows = [];
    var result = false;
    if (validatenull(cols)){
        for(var i=0;i<tabledata.length;i++){
            var rowData = tabledata[i];
            for(var j=0;j<checkedRows.length;j++){
                if (JSON.stringify(rowData) === JSON.stringify(checkedRows[j])) {
                    result =  true;
                    break;
                }
            }
            checkedRows.push(rowData);
        }
    }else{
        var colData = [];
        var colarr = cols.split(",");
        for(var i=0;i<tabledata.length;i++){
            var obj = {};
            for(var j=0;j<colarr.length;j++){
                obj[colarr[j]] = tabledata[i][colarr[j]];
            }
            colData.push(obj);
        }
        for(var i=0;i<colData.length;i++){
            var rowData = colData[i];
            for(var j=0;j<checkedRows.length;j++){
                if (JSON.stringify(rowData) === JSON.stringify(checkedRows[j])) {
                    result =  true;
                    msgWarn('第'+(i+1)+','+(j+1)+'行数据重复!')
                    break;
                }
            }
            checkedRows.push(rowData);
        }
    }
    return result;
}

/**
 * 根据字段cols1判断某行数据cols2是否不相同  cols1\cols2均可填多个  用","隔开  必填
 * @param detailNumber  明细表号码
 * @param cols1  根据字段(组)
 * @param cols2  判断字段(组)
 * @param msg  自定义提示信息
 */
function checkRowExistDiffWithCols(detailNumber,cols1,cols2,msg){
    if (validatenull(msg)){
        msg = "未通过校验!"
    }
    if (validatenull(cols1)||validatenull(cols2)){
        msgBox("未选择校验字段!");
        return;
    }
    const arr1 = cols1.split(",");
    const arr2 = cols2.split(",");
    let unpass = false;
    const checkedData = {};
    const rows = getRowIndexStr(detailNumber);
    for(let i=0; i<rows.length; i++){
        var obj = {};
        var val = {};
        var objVal = [];
        for(var j=0;j<arr1.length;j++){
            obj[arr1[j]] = getFieldValue(arr1[j],rows[i],detailNumber);
            objVal.push(getFieldValue(arr1[j],rows[i],detailNumber));
        }
        for(var j=0;j<arr2.length;j++){
            val[arr2[j]] = getFieldValue(arr2[j],rows[i],detailNumber);
        }
        if (!checkedData.hasOwnProperty(JSON.stringify(obj))){
            checkedData[JSON.stringify(obj)] = JSON.stringify(val);
        }else{
           if ( checkedData[JSON.stringify(obj)]!==JSON.stringify(val)){
               unpass = true;
               msg = objVal.join("|")+" "+msg;
               msgBox(msg)
               break;
           }
        }
    }
    return unpass;
}

/**
 * 明细表按照多个字段进行分组并汇总指定列的值
 * @param detailNumber  明细表号
 * @param groupbycol   需要依据汇总的列名  多个用“,”隔开
 * @param sumcol    需要汇总的数字列
 * @returns {array}  返回汇总后的数组
 * 用例  detailGroupByExtra(3,'zy,zj','rghj');
 */
function detailGroupByExtra(detailNumber,groupbycol,sumcol){
    var detaildata =getRowsDataExtraOA(detailNumber);
    var keys = groupbycol.split(",");
    var mergedData = {};
    for(var i=0;i<detaildata.length;i++){
        var keyStrArr = [];
        for(var j=0;j<keys.length;j++){
            keyStrArr.push(detaildata[i][keys[j]])
        }
        if (!mergedData.hasOwnProperty(keyStrArr.join(","))){
            mergedData[keyStrArr.join(",")] = parseFloat(detaildata[i][sumcol]);
        }else{
            var oldVal = parseFloat(mergedData[keyStrArr.join(",")]);
            oldVal += parseFloat(detaildata[i][sumcol])
            mergedData[keyStrArr.join(",")] = oldVal;
        }
    }
    const resArr = Object.entries(mergedData).map(([keys_,v])=>{
        var arr = keys_.split(",");
        var obj = {};
        for (var n=0;n<keys.length;n++){
           /*     okey+="_";
                obj[okey] = arr[n]+"|"+getShowNameOA(keys[n],1,detailNumber);
            }else{*/
                obj[keys[n]] = arr[n];
        }
        obj[sumcol] = v;
        return obj
    });
    return resArr;
}

/**
 * 按照指定字段汇总明细行数据并得到汇总结果
 * @param detailNumber  明细表号码
 * @param groupbycol  group by的字段
 * @param sumcol   需要汇总的字段  如果为多个用“,”隔开
 * @returns {{}}
 */
function detailGroupBy(detailNumber,groupbycol,sumcol){
    var obj = {};
    var rows = getRowIndexStr(detailNumber);
    for(var i=0;i<rows.length;i++){
        if (!obj.hasOwnProperty(getFieldValue(groupbycol,rows[i],detailNumber))){
            if (!contains(sumcol,",")){
                if (validatenull(getFieldValue(sumcol,rows[i],detailNumber))){
                    obj[getFieldValue(groupbycol,rows[i],detailNumber)] = parseFloat("0");
                }else{
                    obj[getFieldValue(groupbycol,rows[i],detailNumber)] = parseFloat(getFieldValue(sumcol,rows[i],detailNumber));
                }
            }else {
                var arr = sumcol.split(",");
                var _sum = 0;
                for(var j=0;j<arr.length;j++){
                    var val = getFieldValue(arr[j],rows[i],detailNumber);
                    if (validatenull(val)){
                        val = "0";
                    }
                    _sum+=parseFloat(val);
                }
                obj[getFieldValue(groupbycol,rows[i],detailNumber)] =_sum;
            }
        }else{
            var sum = obj[getFieldValue(groupbycol,rows[i],detailNumber)];
            if (!contains(sumcol,",")){
                var val = getFieldValue(sumcol,rows[i],detailNumber);
                if (validatenull(val)){
                    val = "0";
                }
                sum+=parseFloat(val);
            }else {
                var arr = sumcol.split(",");
                var _sum = 0;
                for(var j=0;j<arr.length;j++){
                    var val = getFieldValue(arr[j],rows[i],detailNumber);
                    if (validatenull(val)){
                        val = "0";
                    }
                    _sum+=parseFloat(val);
                }
                sum+=_sum;
            }
            obj[getFieldValue(groupbycol,rows[i],detailNumber)] = sum;
        }
    }
    return obj;
}


//*****************************************自定义业务逻辑end**********************************************//
//*****************************************自定义渲染start*******************************************************//
/**
 * Tooltipster  https://www.jq22.com/yanshi14735
 * @param config  包含几个参数    如下 默认只渲染明细表
 *             theme: 'tooltipster-shadow',//tooltipster-default   //tooltipster-shadow
 *             mode:"overlen", //default  默认(全部加气泡)//abbr  缩略 // overlen超长加气泡
 *             animation: 'fade',  //淡入淡出
 *             delay: 200,  //延迟时间
 *             trigger: 'hover',  //'hover','click','custom'
 *             onlyDetail:true  //是否只是明细表渲染
 * @param renderFields  指定字段渲染 格式为字符串如 'wlms,bb,fjbm'
 */
function toolTipsConfig(config,renderFields_,detailNumber){
        if (validatenull(config)){
            config = {};
        }
        let renderFields;
        if (validatenull(renderFields_)) {
            renderFields = [];
        } else {
            renderFields = renderFields_.split(",");
        }
        var script = document.createElement('script');
        script.src = '/workflow/exceldesign/js/tooltipster.bundle.js';
        document.body.appendChild(script);
        const link = document.createElement('link')
        link.type = 'text/css'
        link.rel = 'stylesheet'
        link.href = "/workflow/exceldesign/css/tooltipster.bundle.min.css"
        document.head.appendChild(link);
        const link1 = document.createElement('link')
        link1.type = 'text/css'
        link1.rel = 'stylesheet'
        link1.href = "/workflow/exceldesign/css/tooltipster-sideTip-shadow.min.css"
        document.head.appendChild(link1);
        setTimeout(function (){
            let target = {
                theme: 'tooltipster-shadow',//tooltipster-default   //tooltipster-shadow
                mode:"overlen", //default  默认(全部加气泡)//abbr  缩略 // overlen超长加气泡
                animation: 'fade',  //淡入淡出
                delay: 200,  //延迟时间
                trigger: 'hover',  //'hover','click','custom'
                onlyDetail:true  //是否只是明细表渲染
            };
            config = smartMerge(config,target);
            if (config.onlyDetail){
                if (validatenull(renderFields)){
                    var items = $(".excelDetailTable").find(".etype_3_swapDiv");
                    for(var i=0;i<items.length;i++){
                        var item = $(items[i]);
                        if (!validatenull(item.attr("data-fieldmark"))){
                            var value = item.find("input")[0].value;
                            if (!validatenull(value)){
                                item.attr("title",value)
                                item.addClass("tooltipOA")
                            }
                        }
                    }
                }else{
                    renderFields.forEach(col=>{
                        var json = getFieldIdAndDetail(col,detailNumber);
                        var rows = getRowIndexStr(json.detailNumber);
                        rows.forEach(rowIndex=>{
                            if (!validatenull(getFieldValue(json.id+'_'+rowIndex))){
                                $("div[data-fieldmark='"+json.id+'_'+rowIndex+"']").attr("title",getFieldValue(json.id+'_'+rowIndex));
                                $("div[data-fieldmark='"+json.id+'_'+rowIndex+"']").addClass("tooltipOA");
                            }
                        });
                    });
                }
                $('.tooltipOA').tooltipster({
                    theme: config.theme ,//shadow
                    animation: config.animation,
                    delay: config.delay,
                    trigger:config.trigger
                });
            }else{
                if (validatenull(renderFields)){
                    for(var i=0;i<$(".etype_3_swapDiv").length;i++){
                        var item = $($(".etype_3_swapDiv")[i]);
                        if (!validatenull(item.attr("data-fieldmark"))){
                            item.attr("title",getFieldValue(item.attr("data-fieldmark")))
                            item.addClass("tooltipOA")
                        }
                    }
                }else{
                    renderFields.forEach(col=>{
                        var json = getFieldIdAndDetail(col,detailNumber);

                        if (!validatenull(getFieldValue(json.id))){
                            $("div[data-fieldmark='"+json.id+"']").attr("title",getFieldValue(json.id));
                            $("div[data-fieldmark='"+json.id+"']").addClass("tooltipOA");
                        }
                    });
                }
                $('.tooltipOA').tooltipster({
                    theme: config.theme ,//shadow
                    animation: config.animation,
                    delay: config.delay,
                    trigger:config.trigger
                });
            }
        },1000)
}

/**
 * 防止按钮被快速多次点击
 * @param buttonName
 * @param time
 */
function setSmartButton(buttonName,time){
    $("button[title='"+buttonName+"']").attr("disabled", true);
    setTimeout(()=> {
        $("button[title='"+buttonName+"']").removeAttr("disabled");
    },time)
}


/**
 * @description 修改字段所在的样式，同时支持主表和明细表字段 （注意动态改变字段的只读必填属性会使样式失效 需要重新设置）****
 * @param name
 * @param config 可不传 不传恢复默认样式
 * config可选值 下面列出的均为默认值 可以自行设定想要的效果 config的属性值与CSS中的样式属性含义相同
 * config={
 *      color:"#123885", //默认颜色 支持H5 CSS颜色样式 如 red blue green... 或颜色值如#FFFFF 、#123456或rgb(18, 56, 133) 在线调色板 https://www.sojson.com/web/panel.html#google_vignette
 *      fontSize:"12px", //字体大小 支持px及pt 默认字体大小为12px或9pt
 *      fontWeight:"400", //粗度 默认不加粗即为400
 *      fontFamily:"Microsoft YaHei",//字体家族 默认微软雅黑
 *      fontVariant:"normal", //字体变形
 *      lineHeight:"normal", //字体行高 默认 normal
 *      textDecoration:"none solid rgb(18, 56, 133)" //文本装饰 如underline为加下划线
 * }
 * config传参时，如果仅改变某几个属性，那么剩余的属性无需传输，如想将字段kpzt颜色改为绿色则，config={'color':'green'} 或将green更换为你想要的其他颜色值
 * ****本方法对字段值改变事件已做监听 所以无需再做监听方法改变样式****
 * ****本方法还存在的问题是当选择浏览框类字段时 点击输入然后点击空白部分使其失去焦点将会使样式消失****
 */
function setFieldStyle(name,config = {}){
    var _config = {
        color:"#123885", //默认颜色  蓝色
        fontSize:"12px", //字体大小
        fontWeight:"400",   //粗度
        fontFamily:"Microsoft YaHei",//字体家族 默认微软雅黑
        fontVariant:"normal", //字体变形
        lineHeight:"normal", //字体行高 默认 normal
        textDecoration:"none solid rgb(18, 56, 133)",  //文本装饰
        //focus:{   //针对性设置 待做 还未实现  针对具体某一个选项设置样式
        //    index:
        //}
    }
    config = smartMerge(config,_config)
    var detailNumber = validatenull(config.detailNumber)?"":config.detailNumber;
  var json = getFieldIdAndDetail(name,detailNumber);
  var setFunc = function (json,config){
      if (!validatenull(json)&&json.hasOwnProperty("id")){
          var id = json.id;
          var isDetail = json.isDetail;
          if (!isDetail){//主表字段
              var _id = id.replace("field","");
              var fieldInfo = WfForm.getFieldInfo(_id)
              if (fieldInfo.hasOwnProperty("browserattr")){
                  if(fieldInfo.detailtype==1||fieldInfo.detailtype==17){//人力资源和多人力资源
                      var css = {
                          "color":config.color,
                          "font-size":config.fontSize,
                          "font-weight":config.fontWeight,
                          "font-family":config.fontFamily,
                          "font-variant":config.fontVariant,
                          "line-height":config.lineHeight,
                          //"text-decoration":config.textDecoration+"!important"
                      }
                      $("#"+id+"span").find('a').css(css);
                      var as = $("#"+id+"span").find('a');
                      for(var i=0;i<as.length;i++){
                          var style =  $(as[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(as[i]).attr("style",style);
                      }
                  }else if (fieldInfo.detailtype==161||fieldInfo.detailtype==162)//自定义单选和多选
                  {
                      var css = {
                          "color":config.color,
                          "font-size":config.fontSize,
                          "font-weight":config.fontWeight,
                          "font-family":config.fontFamily,
                          "font-variant":config.fontVariant,
                          "line-height":config.lineHeight,
                          //"text-decoration":config.textDecoration+"!important"
                      }
                      $("#"+id+"span").find('a').css(css);
                      var as = $("#"+id+"span").find('a');
                      for(var i=0;i<as.length;i++){
                          var style =  $(as[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(as[i]).attr("style",style);
                      }
                  }else if (fieldInfo.detailtype==2||fieldInfo.detailtype==290||fieldInfo.detailtype==19){
                      var css = {
                          "color":config.color,
                          "font-size":config.fontSize,
                          "font-weight":config.fontWeight,
                          "font-family":config.fontFamily,
                          "font-variant":config.fontVariant,
                          "line-height":config.lineHeight,
                          //"text-decoration":config.textDecoration+"!important"
                      }
                      $("div[data-fieldmark=\""+id+"\"]").find("span.text").css(css)
                      $("div[data-fieldmark=\""+id+"\"]").find("span.child-item").css(css)
                      var spans = $("div[data-fieldmark=\""+id+"\"]").find("span.text");
                      var spansReadOnly = $("div[data-fieldmark=\""+id+"\"]").find("span.child-item");
                      for(var i=0;i<spans.length;i++){
                          var style =  $(spans[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(spans[i]).attr("style",style);
                      }
                      for(var i=0;i<spansReadOnly.length;i++){
                          var style =  $(spansReadOnly[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(spansReadOnly[i]).attr("style",style);//此处存在一个优化点如果切换字段的只读必填属性会自动恢复为默认样式 这点可以考虑以后优化
                      }
                  }
              }else if (fieldInfo.hasOwnProperty("selectattr")){
                  var css = {
                      "color":config.color,
                      "font-size":config.fontSize,
                      "font-weight":config.fontWeight,
                      "font-family":config.fontFamily,
                      "font-variant":config.fontVariant,
                      "line-height":config.lineHeight,
                      //"text-decoration":config.textDecoration+"!important"
                  }
                  $("div[data-fieldmark='"+id+"'] span:not(:empty)").css(css);
                  var spans = $("div[data-fieldmark='"+id+"'] span:not(:empty)");
                  for(var i=0;i<spans.length;i++){
                      var style =  $(spans[i]).attr("style")
                      style=style+"text-decoration:"+config.textDecoration+"!important;";
                      $(spans[i]).attr("style",style);
                  }
                  $("div[data-fieldmark='"+id+"']").find("div.ant-select-selection-selected-value").css(css);
                  var divs = $("div[data-fieldmark='"+id+"']").find("div.ant-select-selection-selected-value");
                  for(var i=0;i<divs.length;i++){
                      var style =  $(divs[i]).attr("style")
                      style=style+"text-decoration:"+config.textDecoration+"!important;";
                      $(divs[i]).attr("style",style);
                  }
              }else{//文本
                  var css = {
                      "color":config.color,
                      "font-size":config.fontSize,
                      "font-weight":config.fontWeight,
                      "font-family":config.fontFamily,
                      "font-variant":config.fontVariant,
                      "line-height":config.lineHeight,
                      //"text-decoration":config.textDecoration+"!important"
                  }
                  $("#"+id+"span").css(css)
                  $("#"+id+"span").parent().find("input").css(css)
                  var style =  $("#"+id+"span").attr("style")
                  style=style+"text-decoration:"+config.textDecoration+"!important;";
                  $("#"+id+"span").attr("style",style);
                  var  style1 = $("#"+id+"span").parent().find("input").attr("style");
                  style1=style1+"text-decoration:"+config.textDecoration+"!important;";
                  $("#"+id+"span").parent().find("input").attr("style",style1);
              }
          }else{//明细表字段
              var _id = id.replace("field","");
              var fieldInfo = WfForm.getFieldInfo(_id)
              if (fieldInfo.hasOwnProperty("browserattr")){
                  if(fieldInfo.detailtype==1||fieldInfo.detailtype==17){//人力资源和多人力资源
                      var css = {
                          "color":config.color,
                          "font-size":config.fontSize,
                          "font-weight":config.fontWeight,
                          "font-family":config.fontFamily,
                          "font-variant":config.fontVariant,
                          "line-height":config.lineHeight,
                          //"text-decoration":config.textDecoration+"!important"
                      }
                        $("div[data-fieldname=\""+name+"\"]").find("a").css(css)

                      var as = $("div[data-fieldname=\""+name+"\"]").find("a")
                      for(var i=0;i<as.length;i++){
                          var style =  $(as[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(as[i]).attr("style",style);
                      }

                  }else if (fieldInfo.detailtype==161||fieldInfo.detailtype==162)//自定义单选和多选
                  {
                      var css = {
                          "color":config.color,
                          "font-size":config.fontSize,
                          "font-weight":config.fontWeight,
                          "font-family":config.fontFamily,
                          "font-variant":config.fontVariant,
                          "line-height":config.lineHeight,
                          //"text-decoration":config.textDecoration+"!important"
                      }
                      $("div[data-fieldname=\""+name+"\"]").find("a").css(css)

                      var as = $("div[data-fieldname=\""+name+"\"]").find("a")
                      for(var i=0;i<as.length;i++){
                          var style =  $(as[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(as[i]).attr("style",style);
                      }
                  }else if (fieldInfo.detailtype==2||fieldInfo.detailtype==290||fieldInfo.detailtype==19){//日期时间类型
                      var css = {
                          "color":config.color,
                          "font-size":config.fontSize,
                          "font-weight":config.fontWeight,
                          "font-family":config.fontFamily,
                          "font-variant":config.fontVariant,
                          "line-height":config.lineHeight,
                          //"text-decoration":config.textDecoration+"!important"
                      }
                      $("div[data-fieldname=\""+name+"\"]").find("span.text").css(css)
                      var spans = $("div[data-fieldname=\""+name+"\"]").find("span.text");
                      $("div[data-fieldname=\""+name+"\"]").find("span.child-item").css(css)
                      var spansReadOnly = $("div[data-fieldname=\""+name+"\"]").find("span.child-item");
                      for(var i=0;i<spans.length;i++){
                          var style =  $(spans[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(spans[i]).attr("style",style);
                      }
                      for(var i=0;i<spansReadOnly.length;i++){
                          var style =  $(spansReadOnly[i]).attr("style")
                          style=style+"text-decoration:"+config.textDecoration+"!important;";
                          $(spansReadOnly[i]).attr("style",style);//此处存在一个优化点如果切换字段的只读必填属性会自动恢复为默认样式 这点可以考虑以后优化
                      }
                  }
              }else if (fieldInfo.hasOwnProperty("selectattr")){
                  var css = {
                      "color":config.color,
                      "font-size":config.fontSize,
                      "font-weight":config.fontWeight,
                      "font-family":config.fontFamily,
                      "font-variant":config.fontVariant,
                      "line-height":config.lineHeight,
                      //"text-decoration":config.textDecoration+"!important"
                  }
                  $("div[data-fieldname='"+name+"'] span:not(:empty)").css(css);
                  var spans = $("div[data-fieldname='"+name+"'] span:not(:empty)");
                  for(var i=0;i<spans.length;i++){
                      var style =  $(spans[i]).attr("style")
                      style=style+"text-decoration:"+config.textDecoration+"!important;";
                      $(spans[i]).attr("style",style);
                  }
                  $("div[data-fieldname='"+name+"']").find("div.ant-select-selection-selected-value").css(css);
                  var divs = $("div[data-fieldname='"+name+"']").find("div.ant-select-selection-selected-value");
                  for(var i=0;i<divs.length;i++){
                      var style =  $(divs[i]).attr("style")
                      style=style+"text-decoration:"+config.textDecoration+"!important;";
                      $(divs[i]).attr("style",style);
                  }
              }else{//文本
                  var css = {
                      "color":config.color,
                      "font-size":config.fontSize,
                      "font-weight":config.fontWeight,
                      "font-family":config.fontFamily,
                      "font-variant":config.fontVariant,
                      "line-height":config.lineHeight,
                      //"text-decoration":config.textDecoration+"!important"
                  }
                  $("div[data-fieldname=\""+name+"\"]").find("span").css(css)
                  $("div[data-fieldname=\""+name+"\"]").parent().find("input").css(css)
                  var style =  $("div[data-fieldname=\""+name+"\"]").attr("style")
                  style=style+"text-decoration:"+config.textDecoration+"!important;";
                  $("div[data-fieldname=\""+name+"\"]").attr("style",style);
                  var  style1 = $("div[data-fieldname=\""+name+"\"]").parent().find("input").attr("style");
                  style1=style1+"text-decoration:"+config.textDecoration+"!important;";
                  $("div[data-fieldname=\""+name+"\"]").parent().find("input").attr("style",style1);
              }
          }
      }else{
          console.error("未查询到"+name+"所在字段");
      }
  }
  setFunc(json,config);
  if (!json.isDetail){
      setFieldListener(name,function (obj,id,value){
         if (!validatenull(value)){
             var count = 0;
             var timer = setInterval(function (){
                 count++
                 setFunc(json,config)
                 if (count>=15){
                     clearInterval(timer)
                 }
             },50)
         }
     })
  }else{
      setFieldListener(name,function (id,rowIndex,value){
          if (!validatenull(value)){
              var count = 0;
              var timer = setInterval(function (){
                  count++
                  setFunc(json,config)
                  if (count>=15){
                      clearInterval(timer)
                  }
              },50)
          }
      },config.detailNumber)
  }
}



/*var config = {
    initialColor:"initial",
    blinkColor:"#cccccc",
    longBlinkCssName:"OA_TD_BLINK", //长时闪烁样式名  默认无需更改
    timeBlinkCssName:"OA_TD_BLINK_TIME",//计时闪烁样式名  默认无需更改
    freq:1,//闪烁频率  默认1秒闪烁一次
    kfName:"blinkBackground"  //keyframes的名称 默认取blinkBackground+字段名
}*/
/**
 * 默认闪烁样式设置 可以自定义样式
 * @param config
 */
function setBlinkStyle(config = {}){
    var defaultConfig =  {
        initialColor:"initial",
        blinkColor:"#f4f4f4",
        longBlinkCssName:"OA_TD_BLINK", //长时闪烁样式名  默认无需更改
        timeBlinkCssName:"OA_TD_BLINK_TIME",//计时闪烁样式名  默认无需更改
        freq:1,//闪烁频率  默认1秒闪烁一次
        kfName:"blinkBackground"
    }
    config = smartMerge(config,defaultConfig);
    var styleElement = document.createElement('style');
    styleElement.id = "oa_blink_style";
    styleElement.innerHTML = `  @keyframes `+config.kfName +`{
    0% {
      background-color: `+config.initialColor+` !important;
    }
    50% {
      background-color: `+config.blinkColor+` !important;
    }
    100% {
      background-color: `+config.initialColor+` !important;
    }
  }
  .`+config.longBlinkCssName+` {
    background-color: `+config.initialColor+` !important;
    animation: `+config.kfName+` `+config.freq+`s infinite;
  }
  .`+config.timeBlinkCssName+` {
    background-color: `+config.initialColor+` !important;
    animation: `+config.kfName+` `+config.freq+`s infinite;
  }`;
    document.head.appendChild(styleElement);
}

/**
 * 设置闪烁  （待完成）
 * @param name
 * @param rowIndex
 * @param detailNumber
 * @param isLabel
 */
function setBlink(name,rowIndex,detailNumber,isLabel = false){
    var json = getFieldIdAndDetail(name,detailNumber);
    if(json.isDetail){

    }else{
        var $element = $("div[data-fieldmark='"+json.id+"']").parent();
        var classes = $element.attr('class').split(/\s+/); // 分割class字符串成数组
        var class_ = "";
        classes.some(function(className) {
            if(className.startsWith('mainTd')){
                class_ =  className;
            }
        });
        console.log(class_);
    }
}

/**
 * 为指定明细表添加按钮
 * @param detailNumber  明细表号码
 * @param icon   图标
 * @param title   按钮title
 * @param callbackName   回调方法名称或者方法
 */
function addDetailButton(detailNumber,icon,title,callbackName,extraclass){
    setTimeout(function (){
        var isintervenor  = getUrlParamOA('isintervenor');//是否流程干预
        var ismonitor = getUrlParamOA('ismonitor');//是否流程监控
        if(ismonitor==='1'||isintervenor==='1'){
            return;//流程干预和监控不做操作
        }
        var str;
        if (!validatenull(icon)&&!validatenull(extraclass)){
            icon = icon+" "+extraclass
        }
        var is = $($($("#oTable"+(parseInt(detailNumber)-1)).find("div[data-cellmark='detail_"+detailNumber+"_0_0']")[0]).find("div[class='detailButtonDiv']")[0]).find("i");
        if (is.length==0){
            if (typeof (callbackName)  === 'string'){
                str  ="<i onclick='"+callbackName+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";float: left;\"></i>";
            }else if (callbackName instanceof Function){
                window[callbackName.name] = callbackName;
                str  ="<i onclick='"+callbackName.name+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";float: left;\"></i>"
            }
        }else{
            if (typeof (callbackName)  === 'string'){
                str  ="<i onclick='"+callbackName+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";\"></i>";
            }else if (callbackName instanceof Function){
                window[callbackName.name] = callbackName;
                str  ="<i onclick='"+callbackName.name+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";\"></i>"
            }
        }
        var addEle = $(str);
        $($($("#oTable"+(parseInt(detailNumber)-1)).find("div[data-cellmark='detail_"+detailNumber+"_0_0']")[0]).find("div[class='detailButtonDiv']")[0]).attr("style","min-width: 104px!important;");
        $($($("#oTable"+(parseInt(detailNumber)-1)).find("div[data-cellmark='detail_"+detailNumber+"_0_0']")[0]).find("div[class='detailButtonDiv']")[0]).append(addEle);
    },50)
}

/**
 * 针对界面初始不显示明细表的情况，添加按钮  功能同上
 * @param detailNumber
 * @param icon
 * @param title
 * @param callbackName
 */
function addDetailButton2(detailNumber,icon,title,callbackName,extraclass){
    setTimeout(function (){
        var isintervenor  = getUrlParamOA('isintervenor');//是否流程干预
        var ismonitor = getUrlParamOA('ismonitor');//是否流程监控
        if(ismonitor==='1'||isintervenor==='1'){
            return;//流程干预和监控不做操作
        }
        var str;
        if (!validatenull(icon)&&!validatenull(extraclass)){
            icon = icon+" "+extraclass
        }
        var is = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).find("i");
        if (is.length==0){
            if (typeof (callbackName)  === 'string'){
                str  ="<i onclick='"+callbackName+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";float: left;\"></i>";
            }else if (callbackName instanceof Function){
                window[callbackName.name] = callbackName;
                str  ="<i onclick='"+callbackName.name+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";float: left;\"></i>";
            }
        }else{
            if (typeof (callbackName)  === 'string'){
                str  ="<i onclick='"+callbackName+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";\"></i>";
            }else if (callbackName instanceof Function){
                window[callbackName.name] = callbackName;
                str  ="<i onclick='"+callbackName.name+"()' id=\"button1\" name=\"button1\" class=\""+icon+" detailBtn\" title=\""+title+"\" style=\"font-size:20px;color:white;border-radius:3px;background-color:"+$('.ant-btn-primary').css('background-color')+";\"></i>";
            }
        }
        var addEle = $(str);
        $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).attr("style","min-width: 104px!important;");
        $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).append(addEle)
    },50)
}

/**
 * 在指定明细表头添加指定文字按钮并绑定点击事件
 * @param detailNumber
 * @param txt
 * @param callbackName
 * @param divWidth
 * @param buttonWidth
 */
function addTxtButton(detailNumber,txt,callbackName,divWidth,buttonWidth,extraclass,icon){
    var isintervenor  = getUrlParamOA('isintervenor');//是否流程干预
    var ismonitor = getUrlParamOA('ismonitor');//是否流程监控
    if(ismonitor==='1'||isintervenor==='1'){
        return;//流程干预和监控不做操作
    }
    setTimeout(function (){
        if (validatenull(divWidth)){
            divWidth = 200;
        }
        if (validatenull(extraclass)){
            extraclass = "";
        }
        $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).attr("style","min-width: "+divWidth+"px!important;");
        $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).attr("style","min-width: "+divWidth+"px!important;");
        var childs = $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).children();
        var childs2 = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).children();
        for(var i=0;i<childs.length;i++){
            var oldstyle = $(childs[i]).attr("style");
            var newstyle;
            if (validatenull(oldstyle)){
                newstyle = "float:left";
            }else{
                newstyle = oldstyle+";float:left";
            }
            if (!validatenull(extraclass)){
                $(childs[i]).addClass(extraclass);
            }
            $(childs[i]).attr("style",newstyle);
        }
        for(var i=0;i<childs2.length;i++){
            var oldstyle = $(childs2[i]).attr("style");
            var newstyle;
            if (validatenull(oldstyle)){
                newstyle = "float:left";
            }else{
                newstyle = oldstyle+";float:left";
            }
            if (!validatenull(extraclass)){
                $(childs2[i]).addClass(extraclass);
            }
            $(childs2[i]).attr("style",newstyle);
        }
        var addEle;
        if (validatenull(icon)){
            addEle = "<button onclick=\""+callbackName+"(this)\" id=\"\" type=\"button\" title = \""+txt+"\"  class=\""+extraclass+"\" style=\"float:left;margin-left:4px;height:20px;width:"+buttonWidth+"px;background-color:"+$('.ant-btn-primary').css('background-color')+";border:0;border-radius:3px;cursor: pointer\"><span style=\"color:white\">"+txt+"</span></button>"
        }else{
            addEle = "<button onclick=\""+callbackName+"(this)\" id=\"\" type=\"button\" title = \""+txt+"\"  class=\""+extraclass+"\" style=\"float:left;margin-left:4px;height:20px;width:"+buttonWidth+"px;background-color:"+$('.ant-btn-primary').css('background-color')+";border:0;border-radius:3px;cursor: pointer\"><i class=\"anticon "+icon+"\" style=\"color:white;font-size:10px;\"></i><span style=\"color:white;margin-left:2px;\">"+txt+"</span></button>"
        }
        $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).append(addEle);
            //判断是否已存在按钮已存在则不添加
        //判断是否已存在按钮已存在则不添加
        var buttons = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).find("button[title='"+txt+"']")
        if(buttons.length==0){
            $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).append(addEle)
        }
        var buttons1 = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[1]).find("button[title='"+txt+"']")
        if(buttons1.length==0){
            $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[1]).append(addEle)
        }
    },50)
}

/**
 * 在指定明细表头添加指定文字按钮并绑定点击事件  流程监控页面显示
 * @param detailNumber
 * @param txt
 * @param callbackName
 * @param divWidth
 * @param buttonWidth
 */
function addTxtButton2(detailNumber,txt,callbackName,divWidth,buttonWidth,extraclass,icon){
    setTimeout(function (){
        if (validatenull(divWidth)){
            divWidth = 200;
        }
        if (validatenull(extraclass)){
            extraclass = "";
        }
        $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).attr("style","min-width: "+divWidth+"px!important;");
        $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).attr("style","min-width: "+divWidth+"px!important;");
        var childs = $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).children();
        var childs2 = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).children();
        for(var i=0;i<childs.length;i++){
            var oldstyle = $(childs[i]).attr("style");
            var newstyle;
            if (validatenull(oldstyle)){
                newstyle = "float:left";
            }else{
                newstyle = oldstyle+";float:left";
            }
            if (!validatenull(extraclass)){
                $(childs[i]).addClass(extraclass);
            }
            $(childs[i]).attr("style",newstyle);
        }
        for(var i=0;i<childs2.length;i++){
            var oldstyle = $(childs2[i]).attr("style");
            var newstyle;
            if (validatenull(oldstyle)){
                newstyle = "float:left";
            }else{
                newstyle = oldstyle+";float:left";
            }
            if (!validatenull(extraclass)){
                $(childs2[i]).addClass(extraclass);
            }
            $(childs2[i]).attr("style",newstyle);
        }
        var addEle;
        if (validatenull(icon)){
            addEle = "<button onclick=\""+callbackName+"(this)\" id=\"\" type=\"button\" title = \""+txt+"\"  class=\""+extraclass+"\" style=\"float:left;margin-left:4px;height:20px;width:"+buttonWidth+"px;background-color:"+$('.ant-btn-primary').css('background-color')+";border:0;border-radius:3px;cursor: pointer\"><span style=\"color:white\">"+txt+"</span></button>"
        }else{
            addEle = "<button onclick=\""+callbackName+"(this)\" id=\"\" type=\"button\" title = \""+txt+"\"  class=\""+extraclass+"\" style=\"float:left;margin-left:4px;height:20px;width:"+buttonWidth+"px;background-color:"+$('.ant-btn-primary').css('background-color')+";border:0;border-radius:3px;cursor: pointer\"><i class=\"anticon "+icon+"\" style=\"color:white;font-size:10px;\"></i><span style=\"color:white;margin-left:2px;\">"+txt+"</span></button>"
        }
        $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).append(addEle);
        //判断是否已存在按钮已存在则不添加
        var buttons = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).find("button[title='"+txt+"']")
        if(buttons.length==0){
            $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).append(addEle)
        }
        var buttons1 = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[1]).find("button[title='"+txt+"']")
        if(buttons1.length==0){
            $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[1]).append(addEle)
        }
    },50)
}


/**
 * @description  为明细表添加模板下载、导入和导出等系统集成按钮和自定义按钮功能
 * @param config  具体配置
 * @param detailNumber  明细表号码
 * @param templateid   模板id对应服务器路径  /data/unstructured/template  下文件的名称也可以传整个文件名 可不填
 * @param templateName  下载的模板中文名称  可不填
 */
/**
 *
 * @description  详细说明如下
 * 一、config中可选项很多  默认配置已满足模板下载、导入、导出功能  即使config不做额外配置 也可以自动生成默认模板、导出excel及导入数据
 * 目前生成的模板和导出数据中存在空格问题  暂未解决  不影响数据导入
 * 参数详细说明：
 * 1.uploadUrl  上传模板指向的OA后端服务路径  默认为"/api/uploadTemplate/uploadExcel"  目前这是我做的一种后端实现源码见http://gitlab.gaoce.cc/oa/weaver.git  GCUploadFIle.java
 * 2.nodataflag  无数据禁止导出标识   true则没有数据禁止导出  false  没有数据也可以导出
 * 3.dcflag  导出按钮是否展示  true为显示  false为隐藏
 * 4.drflag  导入按钮是否展示   true为显示  false为隐藏
 * 5.downflag  模板下载按钮是否展示  true为显示  false为隐藏
 * 6.isSave  导出后是否执行保存操作  true是  false否  默认是
 * 8.copyflag 一键复制按钮是否展示,  默认不展示
 * 9.refreshflag 刷新按钮是否展示   默认不展示
 * 10.dctxt:"导出",//导出按钮显示名及默认值
 * 11.drtxt:"导入",//导入按钮显示名及默认值
 * 12.downtxt:"模板下载",//模板按钮显示名及默认值
 * 13.copytxt:"一键复制",//一键复制按钮显示名及默认值
 * 14.refreshtxt:"刷新",//刷新按钮title名及默认值
 * 15.charttxt:"生成图表",//生成可视化图表
 * 16.chartconfig:[//生成图表配置
 *             {
 *                 type:"bar",//类型  bar 柱状图 category  pie
 *                 column:"",//字段,指定进行聚合展示的字段
 *                 option:{}  额外配置  具体参考echart  https://echarts.apache.org/handbook/zh/how-to/chart-types/bar/basic-bar
 *             }
 *         ]
 * 17.templateid  templateid参数和templateName参数可以再config中指定  也可以再config中指定  如果config中没指定会取入参中的templateid和templateName，如果两者均没有配置  那么模板下载和导入功能默认不能使用  后续可以优化增加默认模板的下载和导入能力
 * 18.before  按钮点击前置事件  可以在这里做一些前置动作  before是一个function
 * 19.chooseAfter  选择文件后执行方法   chooseAfter是一个function
 * 20.doneAfter  导入完成后方法  doneAfter是一个function
 * 21.after  按钮点击后置事件  可以在这里做一些后置动作  after是一个function
 * 22.refresh 点击刷新后执行方法   refresh是一个function
 * 23.description 按钮组之后的额外描述 可以在按钮组后面添加上一行文字描述默认红色
 * 24.descconfig 自定义额外描述配置目前仅做了text形式的额外描述
 *  示例（也为默认配置）：
 *  descconfig:{  //按钮组额外描述配置
 *             type:"text",  //text
 *             style:"float:left;margin-left:10px;color:#cc0000;margin-top:1.5px;",
 *             class:"" //自定义类
 *         }
 * 25.columnsConfig   columnsConfig是用来对导入模板中特殊字段做额外配置用的-->
 * -->比如  明细表中字段存在浏览框型和下载选项型（目前仅单选  多选功能待优化），那么上传模板中不可能填写实际值，而只会填写显示值，所以需要做好对应转换-->
 * --> 25.1 kv 数组 用来存放特殊列字段对象
 * --> 25.1.1 column  列字段名  如wlbm
 * --> 25.1.2 type  字段类型 text 文本  check  选择框  browser  浏览框  浏览框字段类型需要在kv中添加配置，无论显示值和实际值是否相同 见下方wlbm
 * --> 25.1.3 sqlid  支持sqlid写法  用法和sendSql方法相同  需要在OA_CUSTOM_SQL_CONFIG表中配置对应sql
 * --> 25.1.4 eventkey  如果浏览框字段的查询事件标识  是针对需要调用ESB接口类型进行转化使用的  eventjson和eventResKey均是  例如getsapkhxxchsj  这里是获取SAP客户信息事件
 * --> 25.1.5 eventjson  如果浏览框字段的查询请求体    例如"{\"NAME1\":\"%s\"}"  这里是客户名称
 * --> 25.1.6 eventResKey 如果浏览框字段的查询相应结果中我们想要的字段的KEY   例如"KUNNR"  这里是客户编号
 * --> 25.1.7 dict  字典设置   可以针对check类型字段自动将显示值转换为实际值如  将【交付阶段-运维服务-A9001】转为【0】
 * sqlid、eventkey、dict三种方式最好独立使用
 * 当字段类型为check类型时  会优先取dict中的对应值 如果没有配置dict  才取sqlid的再渲染值
 * 当字段类型为browser类型时  会优先取eventkey配置查询接口获取主键值  如果没有配置eventkey、eventjson及eventResKey 才取sqlid的再渲染值
 * config参数示例：
 * columnsConfig:{
 *         kv:[
 *           {
 *                     column:"wlbm",//字段名称  为空忽略
 *                     type:"browser"//字段类型   text 文本  check  选择框  browser  浏览框
 *                 },
 *                 {
 *                     column:"shxmh",//字段名称  为空忽略
 *                     type:"browser"//字段类型   text 文本  check  选择框  browser  浏览框
 *                 },
 *                 {
 *                     column:"clfs",//字段名称  为空忽略
 *                     type:"check",//字段类型   text 文本  check  选择框  browser  浏览框
 *                     dict:{
 *                         //字典设置
 *                         "退料":0,
 *                         "作废":1
 *                     }
 *                 },
 *                 {
 *                     column:"xmjd",//字段名称  为空忽略
 *                     type:"check",//字段类型   text 文本  check  选择框  browser  浏览框
 *                     dict:{
 *                         //字典设置
 *                         "交付阶段-运维服务-A9001":0,
 *                         "交付阶段-整改业务员-D9001":1,
 *                         "运维业务-A001":2,
 *                         "整改业务-D001":3,
 *                         "赠送业务-E001":4
 *                     }
 *                 },
 *                 {
 *                     column:"khxc",//字段名称  为空忽略
 *                     type:"browser",//字段类型   text 文本  check  选择框  browser  浏览框
 *                     eventkey:"getsapkhxxchsj",
 *                     eventjson:"{\"NAME1\":\"%s\"}",
 *                     eventResKey:"KUNNR"
 *                 },
 *                 {
 *                     column:"ck",//字段名称  为空忽略
 *                     type:"browser",//字段类型   text 文本  check  选择框  browser  浏览框
 *                     sqlid:"JT933A5T7TTE93EE353OTO1J5JT3311A"  //支持sqlid写法
 *                 }
 *           ]
 *       }
 * 26.customButtons:自定义按钮组
 *   {
 *      26.1 name:"复制",//按钮名称   文本按钮用  文本按钮和图标按钮不可重复配置如果重复配置默认按照文本按钮进行设置
 *      26.2 title:"",//按钮提示
 *      26.3 icon:"fa fa-copy",//图标按钮  图标按钮用仅图标
 *      26.4 ant_icon:"anticon-upload",//按钮图标，图标+文字形式的按钮，具体图标按钮名称参考【https://1x.ant.design/components/icon/】
 *      26.5 click:function (){//按钮点击方法可支持文本或者function
 *               //复制方法
 *           },
 *          //或
 *         //click:"callbackFuncName"//按钮点击方法
 *   }
 *   ex. {
 *                 name:"复制",//按钮名称   文本按钮用  文本按钮和图标按钮不可重复配置如果重复配置默认按照文本按钮进行设置
 *                 title:"复制",//按钮提示
 *                 ant_icon:"anticon-upload",//具体图标按钮名称参考【https://1x.ant.design/components/icon/】
 *                 click:function (){//按钮点击方法可支持文本或者function
 *                 },
 *                 //或
 *                 //click:"callbackFuncName"//按钮点击方法
 *       },... 可写多个 UI渲染会依次排序
 *
 */
function addImportButton(config,detailNumber,templateid,templateName){
    var defaultConfig = {
        uploadUrl:"/api/uploadTemplate/uploadExcel",//上传路径
        nodataflag:true,//无数据禁止导出标识   true则没有数据禁止导出  false  没有数据也可以导出
        dcflag:true,//导出按钮是否展示  true为显示
        drflag:true,//导入按钮是否展示   true为显示
        downflag:true,//模板下载按钮是否展示
        copyflag:false,//一键复制按钮是否展示,
        refreshflag:false,//刷新按钮是否展示
        chartflag:false,//生成图表按钮是否展示
        isSave:true,//导出后是否执行保存操作  true是  false否  默认是
        excludeHidden:false,//导入导出是否包含隐藏列  默认不包含
        //backimport:false,//是否后台导入数据 默认前台导入即数据通过后台解析 然后返回前台并插入表格但是未入库   后台导入数据会先查询流程数据是否已经入库  如果未入库会先保存然后在后台直接将数据插入表格并清除缓存  页面刷新显示导入的数据
        dctxt:"导出",//导出按钮显示名及默认值
        drtxt:"导入",//导入按钮显示名及默认值
        downtxt:"模板下载",//模板按钮显示名及默认值
        copytxt:"一键复制",//一键复制按钮显示名及默认值
        refreshtxt:"刷新",//刷新按钮title名及默认值
        charttxt:"生成图表",//生成可视化图表
        chartconfig:[
            {
                type:"bar",//类型  bar  category  pie
                column:"",//字段,
                option:{}
            }
        ],//生成图标配置
        templateid:templateid,//模板ID
        templateName:templateName,//下载模板后模板文件名称
        detailNumber:detailNumber,//明细表号标识
        chunkSize:50,//分块大小  前台导入分块
        description:"",//按钮组额外描述
        descconfig:{  //按钮组额外描述配置
            type:"text",  //text
            style:"float:left;margin-left:10px;color:#cc0000;margin-top:1.5px;",
            class:"" //自定义类
        },
        buttonColspan:"",
        before:function (obj){
            //前置方法
        },
        chooseAfter:function (obj){
           //选择文件后执行方法
        },
        doneAfter:function (obj){
            //导入完成后方法
        },
        after:function (obj){
            //后置方法
        },
        refresh:function (){
            //刷新方法
            var getWlbm = function (detail){
                if (validatenull(config.wlbm)){
                    var wlbm =  WfForm.convertFieldNameToId('wlbm',"detail_"+detail);
                    if (validatenull(wlbm)){
                        wlbm =  WfForm.convertFieldNameToId('wl',"detail_"+detail);
                    }
                    if (validatenull(wlbm)){
                        wlbm =  WfForm.convertFieldNameToId('wlbh',"detail_"+detail);
                    }
                    return wlbm;
                }else{
                    return config.wlbm;
                }
            }
            var wlbmid = getWlbm(detailNumber);
            if (validatenull(wlbmid)){
                return;
            }
            var getWlms = function (detail){
                if (validatenull(config.wlms)){
                    var wlms =  WfForm.convertFieldNameToId('wlms',"detail_"+detail);
                    if (validatenull(wlms)){
                        wlms =  WfForm.convertFieldNameToId('wlmc',"detail_"+detail);
                    }
                    if (validatenull(wlms)){
                        wlms =  WfForm.convertFieldNameToId('wlxx',"detail_"+detail);
                    }
                    return wlms;
                }else{
                    return config.wlms;
                }
            }
            var getBb = function (detail){
                if (validatenull(config.bb)){
                    var bb =  WfForm.convertFieldNameToId('bb',"detail_"+detail);
                    if (validatenull(bb)){
                        bb =  WfForm.convertFieldNameToId('wlbb',"detail_"+detail);
                    }
                    return bb;
                }else{
                    return config.bb;
                }
            }
            var getDw = function (detail){
                var dw =  WfForm.convertFieldNameToId('dw',"detail_"+detail);
                if (validatenull(dw)){
                    dw =  WfForm.convertFieldNameToId('wldw',"detail_"+detail);
                }
                if (validatenull(dw)){
                    dw =  WfForm.convertFieldNameToId('jldw',"detail_"+detail);
                }
                if (validatenull(dw)){
                    dw =  WfForm.convertFieldNameToId('jbjldw',"detail_"+detail);
                }
                return dw;
            }
            var getWldj = function (detail){
                if (validatenull(config.dj)){
                    var wldj =  WfForm.convertFieldNameToId('wldj',"detail_"+detail);
                    if (validatenull(wldj)){
                        wldj =  WfForm.convertFieldNameToId('dj',"detail_"+detail);
                    }
                    if (validatenull(wldj)){
                        wldj =  WfForm.convertFieldNameToId('hsdj',"detail_"+detail);
                    }
                    if (validatenull(wldj)){
                        wldj =  WfForm.convertFieldNameToId('hsdjy',"detail_"+detail);
                    }
                    if (validatenull(wldj)){
                        wldj =  WfForm.convertFieldNameToId('jg',"detail_"+detail);
                    }
                    if (validatenull(wldj)){
                        wldj =  WfForm.convertFieldNameToId('wljg',"detail_"+detail);
                    }
                    return wldj;
                }else{
                    return config.dj;
                }
            }
            var getWlhsdj = function (detail){
                if (validatenull(config.hsdj)){
                    var hsdj =  WfForm.convertFieldNameToId('hsdj',"detail_"+detail);
                    if (validatenull(hsdj)){
                        hsdj =  WfForm.convertFieldNameToId('hsdjy',"detail_"+detail);
                    }
                    if (validatenull(hsdj)){
                        hsdj =  WfForm.convertFieldNameToId('hsj',"detail_"+detail);
                    }
                    if (validatenull(hsdj)){
                        hsdj =  WfForm.convertFieldNameToId('hsjy',"detail_"+detail);
                    }
                    return hsdj;
                }else{
                    return config.hsdj;
                }
            }
            var getCgz = function (detail){
                if (validatenull(config.cgz)){
                    var cgz =  WfForm.convertFieldNameToId('cgz',"detail_"+detail);
                    if (validatenull(cgz)){
                        cgz =  WfForm.convertFieldNameToId('cgzdm',"detail_"+detail);
                    }
                    if (validatenull(cgz)){
                        cgz =  WfForm.convertFieldNameToId('cgzmc',"detail_"+detail);
                    }
                    return cgz;
                }else{
                    return config.cgz;
                }
            }
            var getWlzjlb = function (detail){
                if (validatenull(config.wlzjlb)){
                    var wlzjlb =  WfForm.convertFieldNameToId('wlzjlb',"detail_"+detail);
                    if (validatenull(wlzjlb)){
                        wlzjlb =  WfForm.convertFieldNameToId('wlzjlx',"detail_"+detail);
                    }
                    return wlzjlb;
                }else{
                    return config.wlzjlb;
                }
            }
            var getWlzj = function (detail){
                if (validatenull(config.wlzj)){
                    var wlzj =  WfForm.convertFieldNameToId('wlzj',"detail_"+detail);
                    return wlzj;
                }else{
                    return config.wlzj;
                }
            }
            var getCgy = function (detail){
                if (validatenull(config.cgy)){
                    var cgy =  WfForm.convertFieldNameToId('cgy',"detail_"+detail);
                    return cgy;
                }else{
                    return config.cgy;
                }
            }
            var getWwhst = function (detail){
                if (validatenull(config.wwhst)){
                    var wwhst =  WfForm.convertFieldNameToId('wwhst',"detail_"+detail);
                    if (validatenull(wwhst)){
                        wwhst =  WfForm.convertFieldNameToId('whst',"detail_"+detail);
                    }
                    if (validatenull(wwhst)){
                        wwhst =  WfForm.convertFieldNameToId('whdst',"detail_"+detail);
                    }
                    return wwhst;
                }else{
                    return config.wwhst;
                }
            }
            var getWlsx = function (detail){
                if (validatenull(config.wlsx)){
                    var wlsx =  WfForm.convertFieldNameToId('wlsx',"detail_"+detail);
                    return wlsx;
                }else{
                    return config.wlsx;
                }
            }
            var getCgzq = function (detail){
                if (validatenull(config.cgzq)){
                    var cgzq =  WfForm.convertFieldNameToId('cgzq',"detail_"+detail);
                    if (validatenull(cgzq)){
                        cgzq =  WfForm.convertFieldNameToId('gdcgzqt',"detail_"+detail);
                    }
                    if (validatenull(cgzq)){
                        cgzq =  WfForm.convertFieldNameToId('gdcgzq',"detail_"+detail);
                    }
                    return cgzq;
                }else{
                    return config.cgzq;
                }
            }
            var wlmsid = getWlms(detailNumber);
            var dwid = getDw(detailNumber);
            var djid = getWldj(detailNumber);
            var hsdjid = getWlhsdj(detailNumber);
            var wlbbid = getBb(detailNumber);
            var cgzid = getCgz(detailNumber);
            var wlzjlbid = getWlzjlb(detailNumber);
            var wlzjid = getWlzj(detailNumber);
            var cgyid = getCgy(detailNumber);
            var wwhstid = getWwhst(detailNumber)
            var wlsxid = getWlsx(detailNumber)
            var cgzqid = getCgzq(detailNumber)
            var rows = getRowIndexStr(detailNumber);
            for (var i=0;i<rows.length;i++){
                const rowIndex = rows[i]
                const value = WfForm.getFieldValue(wlbmid+"_"+rowIndex);
                let param1 = {};
                //7.主键字段接口名=触发字段变化后的值
                param1['MATNR'] = value;
                param1['DATE_BEGIN'] = getDateLastYearNow();
                param1['DATE_END'] = getDateNow();
                param1['ClientId'] = 'com.gaoce.jt.oa';
                param1['OperationCode'] = 'com.gaoce.jt.sap.mm001.MatnrQuery';
                sendGet(param1,'sapwlmxsjcxsj',true,function(data){
                    var result = JSON.parse(data.result);
                    if (!validatenull(wlmsid)){
                        WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:result.data.list[0].MAKTX});
                    }
                    if (!validatenull(dwid)){
                        WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:result.data.list[0].MEINS});
                    }
                    if (!validatenull(wlbbid)){
                        WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:result.data.list[0].ZWLBB});
                    }
                    if (!validatenull(wlzjlbid)){//物料专家类型
                        WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:result.data.list[0].ZZJD});
                    }
                    if (!validatenull(cgzid)){//采购组
                        WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:result.data.list[0].EKGRP});
                    }
                    if (!validatenull(cgzqid)){//固定采购周期
                        WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:result.data.list[0].APLFZ});
                    }
                    if (!validatenull(wlsxid)){//物料属性
                        var tscg = result.data.list[0].SOBSL;
                        var wlsx = result.data.list[0].BESKZ;
                        if(wlsx=='F'&&tscg=='30'){
                            wlsx='委外';
                        }else if(wlsx=='F'&&tscg!='30'){
                            wlsx='外购';
                        }else if(wlsx=='E'){
                            wlsx='自制';
                        }
                        WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:wlsx});
                    }
                    if (!validatenull(wwhstid)){//未维护视图
                        var sfyt = result.data.list[0].ZSFYT;
                        if(sfyt=='1'){
                            sfyt='';
                        }else if(sfyt=='0'){
                            sfyt='会计';
                        }
                        WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:sfyt});
                    }
                    if (!validatenull(wlzjid)){//物料专家
                        sendSqlAsync("9OE35E9J3EAJE1E5EO5O13ATT5717159",result.data.list[0].ZZJD,function (data){
                            var resJSON = JSON.parse(data.result);
                            if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {
                                    value:  JSON.parse(resJSON.data.body.data)[0].id,
                                    specialobj:[
                                        {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                    ]
                                });
                            }
                        },null,true,1440)
                    }
                    if (!validatenull(cgyid)){//采购员
                        sendSqlAsync("37J911TEO91J57OJE71JTJAOJJ33AETO",result.data.list[0].EKGRP,function (data){
                            var resJSON = JSON.parse(data.result);
                            if (resJSON.data.body.data!="非法请求!"&&resJSON.data.body.data!="[]"){
                                WfForm.changeFieldValue(cgyid+"_"+rowIndex, {
                                    value: JSON.parse(resJSON.data.body.data)[0].id,
                                    specialobj:[
                                        {id: JSON.parse(resJSON.data.body.data)[0].id,name:JSON.parse(resJSON.data.body.data)[0].lastname},
                                    ]
                                });
                            }
                        },null,true,1440)
                    }

                },function (err){
                    msgError("查询物料信息失败！err:"+err)
                },true);
                if (!validatenull(djid)||!validatenull(hsdjid)){
                    var params2 = {};
                    params2['MATNR'] = value;
                    var sszz = WfForm.convertFieldNameToId('sczznew');
                    if (validatenull(sszz)){
                        sszz =  WfForm.convertFieldNameToId('sczznew',"detail_"+detailNumber);
                        if (!validatenull(sszz)){
                            params2['EKORG'] = getFieldValue('sczznew',rowIndex,detailNumber);
                        }
                    }else{
                        params2['EKORG'] = getFieldValue(sszz);
                    }
                    var EKORG = params2.EKORG;
                    if (validatenull(EKORG)){
                        params2.EKORG = "1000" //默认是1000
                    }
                    params2['BUDATE'] = getDateLastYearNow();
                    params2['EUDATE'] = getDateNow();
                    sendGet(params2,'getsapwljg',true,function(data){
                        var result = JSON.parse(data.result);
                        try{
                            WfForm.changeFieldValue(djid+"_"+rowIndex, {value:result.data.BODY[0].ITEM[0].NETPR/result.data.BODY[0].ITEM[0].PEINH});
                            //计算含税价
                            var hsj = (result.data.BODY[0].ITEM[0].NETPR*(1+JXSDMJSON[result.data.BODY[0].ITEM[0].EVERS]))/result.data.BODY[0].ITEM[0].PEINH
                            WfForm.changeFieldValue(hsdjid+"_"+rowIndex, {value:hsj});
                        }catch (e){

                        }
                    },function (err){
                        msgError("查询价格失败:"+err)
                    },true,10);
                }
                console.log("明细表 "+detailNumber+" 未配置刷新方法!将自动使用内置方法");
                if (validatenull(value)){
                    //清空目标字段值
                    WfForm.changeFieldValue(wlmsid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(dwid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(djid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(wlbbid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(cgzid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(wlzjlbid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(wlzjid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(cgyid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(wlsxid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(wwhstid+"_"+rowIndex, {value:null});
                    WfForm.changeFieldValue(cgzqid+"_"+rowIndex, {value:null});
                    continue;
                }
            }
            msgSuccess("已刷新!")
        },
        columnsConfig:{
            //下面部分为例子
            /*kv:[
                {
                    column:"xmjd",//字段名称  为空忽略
                    type:"check",//字段类型   text 文本  check  选择框  browser  浏览框
                    //kvMode:"first", //"first" "index" "last"   未实现待做  目前都取第一个 如果为浏览按钮的话取第一个值还是最后一个值还是指定顺序的值  如果选择了index则需要制定顺序  默认first
                    //index:2,//如果kvMode为index时，指定顺序   指定顺序大于数组长度-1  则取最后一个
                    //multi:false,//是否多选  默认否 即单选
                    //sqlid:"",  //支持sqlid写法
                    //eventkey:"",
                    dict:{//字典设置
                        "交付阶段-运维服务-A9001":0,
                        "交付阶段-整改业务员-D9001":1,
                        "运维业务-A001":2,
                        "整改业务-D001":3,
                        "赠送业务-E001":4
                    }
                },
                {
                    column:"khxc",//字段名称  为空忽略
                    type:"browser",//字段类型   text 文本  check  选择框  browser  浏览框
                    kvMode:"first", //"first" "index" "last"  未实现待做  目前都取第一个 如果为浏览按钮的话取第一个值还是最后一个值还是指定顺序的值  如果选择了index则需要制定顺序  默认first
                    eventkey:"getsapkhxxchsj",
                    eventjson:"{\"NAME1\":\"%s\"}",
                    eventResKey:"KUNNR"
                },
                {
                    column:"ck",//字段名称  为空忽略
                    type:"browser",//字段类型   text 文本  check  选择框  browser  浏览框
                    kvMode:"first", //"first" "index" "last"   未实现待做  目前都取第一个 如果为浏览按钮的话取第一个值还是最后一个值还是指定顺序的值  如果选择了index则需要制定顺序  默认first
                    sqlid:"JT933A5T7TTE93EE353OTO1J5JT3311A"  //支持sqlid写法
                }
            ]*/
        },
        customButtons:[//自定义按钮组
            //{
                //name:"复制",//按钮名称   文本按钮用  文本按钮和图标按钮不可重复配置如果重复配置默认按照文本按钮进行设置
                //title:"",//按钮提示
                //icon:"fa fa-copy",//按钮图标  图标按钮用
                //ant_icon:"anticon anticon-xxx",
                //click:function (){//按钮点击方法可支持文本或者function
                    //复制方法
                //},
                //或
                //click:"callbackFuncName"//按钮点击方法
            //}
        ]
    }
    if (validatenull(config)){
        config = {};
    }
    config = smartMerge(config,defaultConfig)
    if (validatenull(config.detailNumber)){
        //明细表未设置则取默认明细表1
        detailNumber = 1;
    }
    if (validatenull(config.templateid)){
        //如果templateid未设置则直接返回并提示
        console.log("未设置模板id!将自动生成模板并导出数据!");
    }
    if (validatenull(config.templateName)){
        //如果templateid未设置则直接返回并提示
        console.log("未设置模板文件名称!将自动生成模板并导出数据!");
    }
    var uploadUrl = config.uploadUrl;
    if (validatenull(uploadUrl)){
        uploadUrl = "/api/uploadTemplate/uploadExcel"
    }
    var width = $($($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0])).width();
    width+=70;
    if (config.refreshflag){
        width = width+45;
        window['refresh_OA'+detailNumber] = function (obj){
            if (config.refresh instanceof Function){
                config.refresh(detailNumber);
            }else if (typeof config.refresh === 'string'){
                if (validatenull(window[config.refresh])){
                    window[config.refresh](detailNumber);
                }
            }else{
                console.error("未找到对应回调方法或refresh方法配置错误!")
            }
        }
        addDetailButton2(detailNumber,'icon-coms-Update-synchronization',config.refreshtxt,'refresh_OA'+detailNumber,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
        addDetailButton(detailNumber,'icon-coms-Update-synchronization',config.refreshtxt,'refresh_OA'+detailNumber,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
    }
    if (config.chartflag){
        //开启了表格生成
        var script1 = document.createElement('script');
        var script2 = document.createElement('script');
        script2.src = '/workflow/exceldesign/js/echarts.min.js';
        script1.src = '/workflow/exceldesign/js/bootstrap.min.js';
        document.body.appendChild(script1);
        document.body.appendChild(script2);
        const link = document.createElement('link')
        link.type = 'text/css'
        link.rel = 'stylesheet'
        link.href = "/workflow/exceldesign/css/bootstrap.min.css"
        document.head.appendChild(link);
        for(let m=0; m<config.chartconfig.length; m++){
            var modal = "<div class=\"modal ant-modal ant-confirm ant-confirm-confirm\" style=\"touch-action: none; width: 1120px; visibility: visible; top: 160px; left: 420px; margin: 0px;\" tabindex=\"-1\" id = \"chart_modal_OA_"+detailNumber+"\">" +
                "<div class=\"ant-modal-content \">" +
                "<div class=\"ant-modal-body\">" +
                "<div class=\"ant-confirm-body\">" +
                "<div class=\"ant-confirm-header\">" +
                "<i class=\"icon-coms-chart ant-confirm-header-icon\"></i>" +
                "<span class=\"ant-confirm-title wea-f14\" id=\"chart_title_"+detailNumber+"\"></span>"+
                "<i class=\"anticon anticon-cross\" onclick=\"close_chart_"+detailNumber+"()\"></i>" +
                "</div>" +
                "<div class=\"ant-confirm-content\" id='chart_container_OA_"+detailNumber+"'>" +
                "" +
                "</div>" +
                "</div>" +
                "<div class=\"ant-confirm-btns\">" +
                "  <button type=\"button\" class=\"ant-btn ant-btn-primary\" style=\"border:none;background-color:"+$('.ant-btn-primary').css('background-color')+";\" onclick=\"downloadChart_"+detailNumber+"()\" title='下载'><span>下 载</span></button>" +
                "  <button type=\"button\" class=\"ant-btn ant-btn-primary\" onclick=\"copyChart_"+detailNumber+"()\" disabled title='复制到剪切板'><span>复制</span></button>" +
                "  <button type=\"button\" class=\"ant-btn ant-btn-ghost\" onclick=\"close_chart_"+detailNumber+"()\" title='关闭'><span>关 闭</span></button>" +
                "</div>" +
                "</div>" +
                "</div>" +
                "</div>";
            $("body").append($(modal));
            $("#"+"chart_title_"+detailNumber).text("生成图表-"+WfForm.getFieldInfo(getFieldId(config.chartconfig[m].column,false,detailNumber)).fieldlabel)
            window["close_chart_"+detailNumber] = function (){
                $("#chart_modal_OA_"+detailNumber).modal("toggle");
            }
            window['chart_OA'+detailNumber] = function (){
                if (window["detail_chart_OA_"+detailNumber]==null||window["detail_chart_OA_"+detailNumber]==undefined){
                    window["detail_chart_OA_"+detailNumber] = echarts.init(document.getElementById('chart_container_OA_'+detailNumber), null, {
                        width: 1000,
                        height: 450
                    });
                    var getData = function (){
                        var data = [];
                        var rows = getRowIndexStr(detailNumber);
                        for(var j=0;j<rows.length;j++){
                            data.push(validatenull(getShowNameOA(config.chartconfig[m].column,rows[j],detailNumber))?("未知"+j):getShowNameOA(config.chartconfig[m].column,rows[j],detailNumber));
                        }
                        return countElements(data);
                    }
                    var rotate = 0;
                    var length = Object.keys(getData()).join(",").replace(",","").length;
                    if (length<=45){
                        rotate = 0;
                    }else if (length>45&&length<=97){
                        rotate = 10;
                    }else{
                        rotate = 18;
                    }
                    if (validatenull(config.chartconfig[m].option)){
                        var option = {
                            xAxis: {
                                data: Object.keys(getData()),
                                axisLabel: {
                                    rotate: rotate
                                }
                            },
                            yAxis: {},
                            series: [
                                {
                                    type: config.chartconfig[m].type,
                                    data: Object.values(getData()),
                                    label: {
                                        show: true, // 显示数值
                                        position: 'top', // 数值显示的位置
                                        barWidth:"10%",
                                    }
                                }
                            ]
                        }
                        // 导出单个图表图片
                        var Export = function() {
                            var img = new Image();
                            // pieMyChart1 要导出的图表
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            img.onload = function () {
                                var canvas = document.createElement("canvas");
                                canvas.width = img.width;
                                canvas.height = img.height;
                                var ctx = canvas.getContext("2d");
                                ctx.drawImage(img, 0, 0);
                                var dataURL = canvas.toDataURL("image/png");
                                var a = document.createElement("a");
                                var event = new MouseEvent("click");
                                a.download = $("#"+"chart_title_"+detailNumber).text()+".png";
                                // 将生成的URL设置为a.href属性
                                a.href = dataURL;
                                // 触发a的单击事件
                                a.dispatchEvent(event);
                                a.remove();
                            };
                        }
                        window["detail_chart_OA_"+detailNumber].setOption(option);
                        window["downloadChart_"+detailNumber] = function (){
                            Export();
                            msgSuccess("下载完成!");
                            //$("#chart_modal_OA_"+detailNumber).modal("toggle");
                        }
                        window["copyChart_"+detailNumber] = async function (){
                                // 创建一个图片对象
                                const img = new Image();
                                img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                    type: "png",
                                    pixelRatio: 1, //放大2倍
                                    backgroundColor: "#fff",
                                });
                                img.setAttribute('crossOrigin', 'Anonymous');
                                // 等待图片加载完成
                            img.onload = () => {
                                if (img.complete){
                                    const width = img.width;
                                    const height = img.height;
                                    let newCanvas = document.createElement('canvas');
                                    let ctx = newCanvas.getContext('2d');
                                    if(ctx) {
                                        ctx.drawImage(img, width, height);
                                        newCanvas.toBlob(blob => {
                                            navigator.clipboard.write([
                                                new ClipboardItem({
                                                    'image/png': blob,
                                                }),
                                            ]).then(() => {
                                                msgSuccess("已复制到剪切板!");
                                            }).catch((e) => {
                                                msgError(e);
                                            })
                                        }, 'image/png')
                                    }
                                }
                            }
                        }
                    }else{
                        // 导出单个图表图片
                        var Export = function() {
                            var img = new Image();
                            // pieMyChart1 要导出的图表
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            img.onload = function () {
                                var canvas = document.createElement("canvas");
                                canvas.width = img.width;
                                canvas.height = img.height;
                                var ctx = canvas.getContext("2d");
                                ctx.drawImage(img, 0, 0);
                                var dataURL = canvas.toDataURL("image/png");
                                var a = document.createElement("a");
                                var event = new MouseEvent("click");
                                a.download = $("#"+"chart_title_"+detailNumber).text()+".png";
                                // 将生成的URL设置为a.href属性
                                a.href = dataURL;
                                // 触发a的单击事件
                                a.dispatchEvent(event);
                                a.remove();
                            };
                        }
                        window["detail_chart_OA_"+detailNumber].setOption(config.chartconfig[m].option);
                        window["downloadChart_"+detailNumber] = function (){
                            Export()
                            msgSuccess("下载完成!");
                            //$("#chart_modal_OA_"+detailNumber).modal("toggle");
                        }
                        window["copyChart_"+detailNumber] = async function (){
                            // 创建一个图片对象
                            const img = new Image();
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            // 等待图片加载完成
                            img.onload = () => {
                                if (img.complete){
                                    const width = img.width;
                                    const height = img.height;
                                    let newCanvas = document.createElement('canvas');
                                    let ctx = newCanvas.getContext('2d');
                                    if(ctx) {
                                        ctx.drawImage(img, width, height);
                                        newCanvas.toBlob(blob => {
                                            navigator.clipboard.write([
                                                new ClipboardItem({
                                                    'image/png': blob,
                                                }),
                                            ]).then(() => {
                                                msgSuccess("已复制到剪切板!");
                                            }).catch((e) => {
                                                msgError(e);
                                            })
                                        }, 'image/png')
                                    }
                                }
                            }
                        }
                    }
                    $("#chart_modal_OA_"+detailNumber).modal("toggle");
                }else{
                    window["detail_chart_OA_"+detailNumber] = echarts.init(document.getElementById('chart_container_OA_'+detailNumber), null, {
                        width: 1000,
                        height: 450
                    });
                    var getData = function (){
                        var data = [];
                        var rows = getRowIndexStr(detailNumber);
                        for(var j=0;j<rows.length;j++){
                            data.push(validatenull(getShowNameOA(config.chartconfig[m].column,rows[j],detailNumber))?("未知"+j):getShowNameOA(config.chartconfig[m].column,rows[j],detailNumber));
                        }
                        return countElements(data);
                    }
                    var rotate = 0;
                    var length = Object.keys(getData()).join(",").replace(",","").length;
                    if (length<=45){
                        rotate = 0;
                    }else if (length>45&&length<=97){
                        rotate = 10;
                    }else{
                        rotate = 18;
                    }
                    if (validatenull(config.chartconfig[m].option)){
                        var option = {
                            xAxis: {
                                data: Object.keys(getData()),
                                axisLabel: {
                                    rotate: rotate
                                }
                            },
                            yAxis: {},
                            series: [
                                {
                                    type: config.chartconfig[m].type,
                                    data: Object.values(getData()),
                                    label: {
                                        show: true, // 显示数值
                                        position: 'top', // 数值显示的位置
                                        barWidth:"10%",
                                    }
                                }
                            ]
                        }
                        // 导出单个图表图片
                        var Export = function() {
                            var img = new Image();
                            // pieMyChart1 要导出的图表
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            img.onload = function () {
                                var canvas = document.createElement("canvas");
                                canvas.width = img.width;
                                canvas.height = img.height;
                                var ctx = canvas.getContext("2d");
                                ctx.drawImage(img, 0, 0);
                                var dataURL = canvas.toDataURL("image/png");
                                var a = document.createElement("a");
                                var event = new MouseEvent("click");
                                a.download = $("#"+"chart_title_"+detailNumber).text()+".png";
                                // 将生成的URL设置为a.href属性
                                a.href = dataURL;
                                // 触发a的单击事件
                                a.dispatchEvent(event);
                                a.remove();
                            };
                        }
                        window["detail_chart_OA_"+detailNumber].setOption(option);
                        window["downloadChart_"+detailNumber] = function (){
                            Export();
                            msgSuccess("下载完成!");
                        }
                        window["copyChart_"+detailNumber] = async function (){
                            // 创建一个图片对象
                            const img = new Image();
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            // 等待图片加载完成
                            img.onload = () => {
                                if (img.complete){
                                    const width = img.width;
                                    const height = img.height;
                                    let newCanvas = document.createElement('canvas');
                                    let ctx = newCanvas.getContext('2d');
                                    if(ctx) {
                                        ctx.drawImage(img, width, height);
                                        newCanvas.toBlob(blob => {
                                            navigator.clipboard.write([
                                                new ClipboardItem({
                                                    'image/png': blob,
                                                }),
                                            ]).then(() => {
                                                msgSuccess("已复制到剪切板!");
                                            }).catch((e) => {
                                                msgError(e);
                                            })
                                        }, 'image/png')
                                    }
                                }
                            }
                        }
                    }else{
                        var Export = function() {
                            var img = new Image();
                            // pieMyChart1 要导出的图表
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            img.onload = function () {
                                var canvas = document.createElement("canvas");
                                canvas.width = img.width;
                                canvas.height = img.height;
                                var ctx = canvas.getContext("2d");
                                ctx.drawImage(img, 0, 0);
                                var dataURL = canvas.toDataURL("image/png");
                                var a = document.createElement("a");
                                var event = new MouseEvent("click");
                                a.download = $("#"+"chart_title_"+detailNumber).text()+".png";
                                // 将生成的URL设置为a.href属性
                                a.href = dataURL;
                                // 触发a的单击事件
                                a.dispatchEvent(event);
                                a.remove();
                            };
                        }
                        window["detail_chart_OA_"+detailNumber].setOption(config.chartconfig[m].option);
                        window["downloadChart_"+detailNumber] = function (){
                            Export()
                            msgSuccess("下载完成!");
                        }
                        window["copyChart_"+detailNumber] = async function (){
                            // 创建一个图片对象
                            const img = new Image();
                            img.src = window["detail_chart_OA_"+detailNumber].getDataURL({
                                type: "png",
                                pixelRatio: 1, //放大2倍
                                backgroundColor: "#fff",
                            });
                            img.setAttribute('crossOrigin', 'Anonymous');
                            // 等待图片加载完成
                            img.onload = () => {
                                if (img.complete){
                                    const width = img.width;
                                    const height = img.height;
                                    let newCanvas = document.createElement('canvas');
                                    let ctx = newCanvas.getContext('2d');
                                    if(ctx) {
                                        ctx.drawImage(img, width, height);
                                        newCanvas.toBlob(blob => {
                                            navigator.clipboard.write([
                                                new ClipboardItem({
                                                    'image/png': blob,
                                                }),
                                            ]).then(() => {
                                                msgSuccess("已复制到剪切板!");
                                            }).catch((e) => {
                                                msgError(e);
                                            })
                                        }, 'image/png')
                                    }
                                }
                            }
                        }
                    }
                    $("#chart_modal_OA_"+detailNumber).modal("toggle");
                }
            }
        }
        width+=calculateTextLength(config.charttxt)*12*1.3+14;
        addTxtButton2(detailNumber,config.charttxt,'chart_OA'+detailNumber,width.toString()+14,calculateTextLength(config.charttxt)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,"anticon-bar-chart");
    }
    if (config.downflag){
        var script3 = document.createElement('script');
        script3.src = '/workflow/exceldesign/js/OAPinyin.js';
        document.body.appendChild(script3);
            width = width+calculateTextLength(config.downtxt)*12*1.3;
            window['down_OA'+detailNumber] = function (obj){
                //如果配置了模板则下载指定模板 否则生成默认模板
                if (!validatenull(config.templateid)){
                    window.location.href = (getUrlOA()+"/api/downloadTemplete/download?fileName="+config.templateName+"&id="+config.templateid);
                }else{
                    msgLoading("正在生成默认模板...",2);
                    if (validatenull(config.templateName)){
                        //取默认模板名称
                        var spans =  $(obj).closest('td.td_textalign_center').parent().prev().find('span');
                        if (spans.length==0){
                            config.templateName = $('.wea-new-top-req-title-text').find("div").text().split(' - ')[1]+"模板.xls";
                        }else{
                            for(var i=0;i<spans.length;i++){
                                if (!validatenull(spans[i].textContent)&&!validatenull(spans[i].textContent.trim())){
                                    config.templateName = spans[i].textContent+config.drtxt+"模板.xls";
                                    break;
                                }
                            }
                            if (validatenull(config.templateName)){
                                config.templateName = $('#requestmarkSpan').parent()[0].textContent.split(' - ')[1]+"流程-明细表"+detailNumber+config.drtxt+"模板.xls";
                            }
                        }
                    }
                    $.ajax({
                        type: "POST",
                        url: "/api/downloadTemplete/genarateModel",
                        data: {
                            titles:getTitleInfo(detailNumber,config.excludeHidden).join(",")
                        },
                        async:true,
                        dataType:"json",
                        contentType: 'application/x-www-form-urlencoded',
                        success: function(data) {
                            setTimeout(function (){
                                // 处理响应
                                window.location.href = "/api/downloadTemplete/downloadDefaultModel?realFileName="+data.data+"&fileName="+config.templateName;
                                msgSuccess("下载成功!")
                            },1000)
                        },
                        error: function(xhr, status, error) {
                            msgError("下载失败!"+error)
                        }
                    });
                }
            }
        addTxtButton2(detailNumber,config.downtxt,'down_OA'+detailNumber,width.toString()+14,calculateTextLength(config.downtxt)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,"anticon-download");
    }
    if (config.drflag){
        $("button[title='明细导入']").parent().remove();//去除掉系统默认的明细导入按钮  如果存在的话
        $('body').append( $('<div id="fileContainerOA_'+detailNumber+'" style="display:none;"></div>'));
        var $fileUploadBtn = $('<input type="file" id="dynamicFileInputOA_'+detailNumber+'" accept=".xls, .xlsx"/>');
        $('#fileContainerOA_'+detailNumber).append($fileUploadBtn);
        width = width+ 40;
        window['daoru_OA_file_count'+detailNumber] = true;//导入文件标识
        window["daoru_OA_lastTime"+detailNumber] = 0;
        window["daoru_OA_lastSize"+detailNumber] = 0;
        var progressHandle = function (event){
            /*计算间隔*/
            var nowTime = new Date().getTime();
            var intervalTime = (nowTime - window["daoru_OA_lastTime"+detailNumber])/1000;//时间单位为毫秒，需转化为秒
            var intervalSize = event.loaded - window["daoru_OA_lastSize"+detailNumber];

            /*重新赋值以便于下次计算*/
            window["daoru_OA_lastTime"+detailNumber] = nowTime;
            window["daoru_OA_lastSize"+detailNumber] = event.loaded;

            /*计算速度*/
            var speed = intervalSize/intervalTime;
            var bSpeed = speed;//保存以b/s为单位的速度值，方便计算剩余时间
            var units = 'b/s';//单位名称
            if(speed/1024>1){
                speed = speed/1024;
                units = 'k/s';
            }
            if(speed/1024>1){
                speed = speed/1024;
                units = 'M/s';
            }
            /*计算剩余时间*/
            var leftTime = ((event.total - event.loaded) / bSpeed);
            /*计算进度*/
            var progress = event.loaded/event.total * 100;

            console.log("当前进度：" + progress.toFixed(1) + "%    当前速度：" + speed.toFixed(1) + units +"   预计剩余时间：" + leftTime.toFixed(1) + "秒");
        }
        window['daoru_OA'+detailNumber] = function (obj){
            config.before(obj)
            //拉起选择文件
            // 为动态创建的文件上传按钮绑定点击事件
            $('#dynamicFileInputOA_'+detailNumber).click();
            // 监听文件改变事件，以便在文件被选择后进行上传
            $('#dynamicFileInputOA_'+detailNumber).on('change',  function() {
                var file = this.files[0];
                if (file==undefined||file==null||file.name==null||file.name==undefined){
                    return;
                }
                if (!window['daoru_OA_file_count'+detailNumber]){
                    return;
                }
                var allowedExtensions = ['xls', 'xlsx'];
                // 获取文件扩展名
                var fileName = file.name;
                var fileExtension = fileName.split('.').pop().toLowerCase();

                if ($.inArray(fileExtension, allowedExtensions) === -1) {
                    msgWarn('只能上传.xls和.xlsx类型的文件！');
                    // 清除已选择的非法文件
                    $(this).val('');
                    return;
                }
                // 创建FormData对象并添加文件
                var formData = new FormData();
                formData.append('file', file);
                // 使用jQuery的$.ajax方法发起POST请求上传文件
                window['daoru_OA_file_count'+detailNumber] = false;
                WfForm.controlBtnDisabled(true);
                $.ajax({
                    url: "/api/uploadTemplate/uploadExcel",
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    async:true,
                    /*xhr: function () {
                        //获取xhr对象
                        var xhr = $.ajaxSettings.xhr();
                        //检查是否在上传文件
                        if (xhr.upload) {
                            //绑定progress事件的回调函数
                            xhr.upload.addEventListener('progress', progressHandle, false);
                        }
                        //xhr对象返回给jQuery使用
                        return xhr;
                    },*/
                    success: function(response) {
                        msgLoading("正在上传文件并解析文件...请不要关闭表单",300);
                        config.chooseAfter(obj);
                        if (response.code=="0"){
                            let fileName = encodeURIComponent(encodeURIComponent(response.data));
                            let configJson = encodeURIComponent(JSON.stringify(config.columnsConfig.kv));
                            let encodedUrl = "/api/uploadTemplate/analyzeData?fileName="+fileName+"&configJson="+configJson
                            $.ajax({
                                url: encodedUrl,
                                type: 'POST',
                                contentType: 'application/x-www-form-urlencoded',
                                async:true,
                                success: function(response1) {
                                    window.antd.message.destroy();
                                    if (response1==null||response1.code!="0"){
                                        msgError("解析模板数据失败!"+response1.msg);
                                        $(this).val("");
                                        this.value = "";
                                        WfForm.controlBtnDisabled(false);
                                        return;
                                    }
                                    if (response1.data.length==0){
                                        msgError("未解析到任何数据!");
                                        $('#dynamicFileInputOA_'+detailNumber).val("");
                                        $(this).val("");
                                        this.value = "";
                                        WfForm.controlBtnDisabled(false);
                                        return;
                                    }
                                    $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",true);
                                    var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                                    for(var n =0;n<buttons.length;n++){
                                        var style = $(buttons[n]).attr("style");
                                        if (validatenull(style)){
                                            $(buttons[n]).attr("style","cursor: not-allowed;");
                                        }else{
                                            $(buttons[n]).attr("style",style+";cursor: not-allowed;");
                                        }
                                    }
                                    if (response1!=null&&response1.code=="0"){
                                        msgLoading("解析数据成功，正在向明细表 "+detailNumber+" 插入数据...共计"+response1.data.length+"条...请不要关闭表单",300)
                                        //获取到即将导入明细表的数据数组
                                            setTimeout(function (){
                                                addDetailRowOAAsync(detailNumber,response1.data,null,config.chunkSize).then(()=>{
                                                    $('#dynamicFileInputOA_'+detailNumber).val("");
                                                    window.antd.message.destroy();
                                                    msgSuccess(config.drtxt+"成功!共插入"+response1.data.length+"条数据!",3);
                                                    config.after(obj);
                                                    if (config.isSave){
                                                        WfForm.doRightBtnEvent("BTN_WFSAVE");
                                                        setTimeout(function (){
                                                            msgLoading("正在保存数据...请不要关闭表单",3);
                                                        },3100);
                                                    }else{
                                                        WfForm.controlBtnDisabled(false);
                                                        $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",false);
                                                        var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                                                        for(var n =0;n<buttons.length;n++){
                                                            var style = $(buttons[n]).attr("style");
                                                            if (validatenull(style)){
                                                                $(buttons[n]).attr("style","cursor: pointer;");
                                                            }else{
                                                                $(buttons[n]).attr("style",style+";cursor: pointer;");
                                                            }
                                                        }
                                                    }
                                                }) .catch((error) => {
                                                    // 处理异步操作中的错误
                                                    window.antd.message.destroy();
                                                    msgError("解析模板数据失败!"+error);
                                                    $('#dynamicFileInputOA_'+detailNumber).val("");
                                                    $(this).val("");
                                                    this.value = "";
                                                    WfForm.controlBtnDisabled(false);
                                                    $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",false);
                                                    var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                                                    for(var n =0;n<buttons.length;n++){
                                                        var style = $(buttons[n]).attr("style");
                                                        if (validatenull(style)){
                                                            $(buttons[n]).attr("style","cursor: pointer;");
                                                        }else{
                                                            $(buttons[n]).attr("style",style+";cursor: pointer;");
                                                        }
                                                    }
                                                });
                                            },100)
                                    }else{
                                        msgError("解析模板数据失败!"+response1.msg);
                                        $('#dynamicFileInputOA_'+detailNumber).val("");
                                        $(this).val("");
                                        this.value = "";
                                        $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",false);
                                        var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                                        for(var n =0;n<buttons.length;n++){
                                            var style = $(buttons[n]).attr("style");
                                            if (validatenull(style)){
                                                $(buttons[n]).attr("style","cursor: pointer;");
                                            }else{
                                                $(buttons[n]).attr("style",style+";cursor: pointer;");
                                            }
                                        }
                                        WfForm.controlBtnDisabled(false);
                                    }
                                    window['daoru_OA_file_count'+detailNumber] = true;
                                },
                                error: function(xhr, status, error) {
                                    window.antd.message.destroy();
                                    msgError("解析模板数据失败!"+error);
                                    $('#dynamicFileInputOA_'+detailNumber).val("");
                                    $(this).val("");
                                    this.value = "";
                                    $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",false);
                                    var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                                    for(var n =0;n<buttons.length;n++){
                                        var style = $(buttons[n]).attr("style");
                                        if (validatenull(style)){
                                            $(buttons[n]).attr("style","cursor: pointer;");
                                        }else{
                                            $(buttons[n]).attr("style",style+";cursor: pointer;");
                                        }
                                    }
                                    config.after(obj);
                                    window['daoru_OA_file_count'+detailNumber] = true;
                                    WfForm.controlBtnDisabled(false);
                                }
                            });
                        }else{
                            window.antd.message.destroy();
                            msgError("上传文件失败!"+response.msg);
                            $('#dynamicFileInputOA_'+detailNumber).val("");
                            $(this).val("");
                            this.value = "";
                            $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",false);
                            var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                            for(var n =0;n<buttons.length;n++){
                                var style = $(buttons[n]).attr("style");
                                if (validatenull(style)){
                                    $(buttons[n]).attr("style","cursor: pointer;");
                                }else{
                                    $(buttons[n]).attr("style",style+";cursor: pointer;");
                                }
                            }
                            config.after(obj);
                            window['daoru_OA_file_count'+detailNumber] = true;
                            WfForm.controlBtnDisabled(false);
                        }
                    },
                    error: function(xhr, status, error) {
                        msgError("解析模板数据失败!"+error);
                        window['daoru_OA_file_count'+detailNumber] = true;
                        $(this).val("");
                        this.value = "";
                        $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber).prop("disabled",false);
                        var buttons = $("."+"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                        for(var n =0;n<buttons.length;n++){
                            var style = $(buttons[n]).attr("style");
                            if (validatenull(style)){
                                $(buttons[n]).attr("style","cursor: pointer;");
                            }else{
                                $(buttons[n]).attr("style",style+";cursor: pointer;");
                            }
                        }
                        WfForm.controlBtnDisabled(false);
                    }
                });
            });
        }
        addTxtButton2(detailNumber,config.drtxt,'daoru_OA'+detailNumber,width.toString(),calculateTextLength(config.drtxt)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,"anticon-upload");
        width += (calculateTextLength(config.drtxt)*12*1.3+14);
    }
    if (config.nodataflag){
            window["daochu_OA"+detailNumber] = function (obj){
                $(obj).attr("disabled","disabled");
                try{
                    msgLoading("正在"+config.dctxt+"数据...请稍候",300);
                    setTimeout(async function (){
                        var rows = getRowIndexStr(detailNumber);
                        if (rows.length==0){
                            msgDestroy();
                            msgWarn("明细表无数据!");
                            $(obj).removeAttr("disabled");
                            return;
                        }
                        config.before(obj);
                        var checkRows = WfForm.getDetailCheckedRowIndexStr("detail_"+detailNumber);//如果勾选了 则取勾选了的数据进行下载
                        var datas = "";
                        if (validatenull(checkRows)){
                            datas = getRowsShowDatas(detailNumber);
                        }else{
                            datas = getRowsShowDatas(detailNumber,true);
                        }
                        await new Promise(resolve => setTimeout(resolve, 0));
                        $.ajax({
                            type: "POST",
                            url: "/api/export/exportData",
                            data: {
                                templateid:templateid,
                                titles:getTitleInfo(detailNumber,config.excludeHidden).join(","),
                                datas:JSON.stringify(datas)
                            },
                            async:true,
                            dataType:"json",
                            contentType: 'application/x-www-form-urlencoded',
                            success: function(data) {
                                if (validatenull(config.templateName)){
                                    //取默认模板名称
                                    var spans =  $(obj).closest('td.td_textalign_center').parent().prev().find('span');
                                    if (spans.length==0) {
                                        config.templateName = $('.wea-new-top-req-title-text').find("div").text().split(' - ')[1] + "模板.xls";
                                    }else {
                                        for(var i=0;i<spans.length;i++){
                                            if (!validatenull(spans[i].textContent)&&!validatenull(spans[i].textContent.trim())){
                                                config.templateName = spans[i].textContent+config.drtxt+"模板.xls";
                                                break;
                                            }
                                        }
                                    }
                                    if (validatenull(config.templateName)){
                                        config.templateName = $('#requestmarkSpan').parent()[0].textContent.split(' - ')[1]+"流程-明细表"+detailNumber+config.drtxt+"模板.xls";
                                    }
                                }
                                var tempfileName = config.templateName.replace(config.drtxt+"模板","").replace("模板","");
                                window.location.href = "/api/downloadTemplete/downloadExcel?readFileName="+data.data+"&fileName="+tempfileName;
                                msgDestroy();
                                msgSuccess(config.dctxt+"成功!")
                                config.doneAfter(obj);
                                config.after(obj);
                                $(obj).removeAttr("disabled");
                            },
                            error: function(xhr, status, error) {
                                msgError(config.dctxt+"失败!"+error)
                                $(obj).removeAttr("disabled");
                            }
                        });
                    },50);
                }catch (e){
                    $(obj).removeAttr("disabled");
                }
            }
            if (config.dcflag){
                addTxtButton2(detailNumber,config.dctxt,'daochu_OA'+detailNumber,width.toString(),calculateTextLength(config.dctxt)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,"anticon-download");
            }
    }else {
        window["daochu_OA"+detailNumber] = function (obj){
            $(obj).attr("disabled","disabled");
            msgLoading("正在"+config.dctxt+"数据...请稍候",300);
            setTimeout(async function (){
                config.before(obj);
                var checkRows = WfForm.getDetailCheckedRowIndexStr("detail_"+detailNumber);//如果勾选了 则取勾选了的数据进行下载
                var datas = "";
                if (validatenull(checkRows)){
                    datas = getRowsShowDatas(detailNumber);
                }else{
                    datas = getRowsShowDatas(detailNumber,true);
                }
                await new Promise(resolve => setTimeout(resolve, 0));
                $.ajax({
                    type: "POST",
                    url: "/api/export/exportData",
                    data: {
                        templateid:templateid,
                        titles:getTitleInfo(detailNumber,config.excludeHidden).join(","),
                        datas:JSON.stringify(datas)
                    },
                    async:true,
                    dataType:"json",
                    contentType: 'application/x-www-form-urlencoded',
                    success: function(data) {
                        // 处理响应
                        if (validatenull(config.templateName)){
                            //取默认模板名称
                            var spans =  $(obj).closest('td.td_textalign_center').parent().prev().find('span');
                            if (spans.length==0) {
                                config.templateName = $('.wea-new-top-req-title-text').find("div").text().split(' - ')[1] + "模板.xls";
                            }else{
                                for(var i=0;i<spans.length;i++){
                                    if (!validatenull(spans[i].textContent)&&!validatenull(spans[i].textContent.trim())){
                                        config.templateName = spans[i].textContent+config.drtxt+"模板.xls";
                                        break;
                                    }
                                }
                            }
                            if (validatenull(config.templateName)){
                                config.templateName = $('#requestmarkSpan').parent()[0].textContent.split(' - ')[1]+"流程-明细表"+detailNumber+config.drtxt+"模板.xls";
                            }
                        }
                        window.location.href = "/api/downloadTemplete/downloadExcel?readFileName="+data.data+"&fileName="+config.templateName.replace(config.drtxt+"模板","");
                        msgDestroy();
                        msgSuccess(config.dctxt+"成功!")
                        config.doneAfter(obj);
                        config.after(obj);
                        $(obj).removeAttr("disabled");
                    },
                    error: function(xhr, status, error) {
                        msgError(config.dctxt+"失败!"+error)
                        $(obj).removeAttr("disabled");
                    }
                });
            },50)
        }
        if (config.dcflag){
            addTxtButton2(detailNumber,config.dctxt,'daochu_OA'+detailNumber,width.toString(),calculateTextLength(config.dctxt)*12*1.3,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,"anticon-download");
        }
    }
    if (config.copyflag){
        width = width+calculateTextLength(config.copytxt)*12*1.3;
        window["copy_OA"+detailNumber] = function (obj){
            WfForm.showConfirm("确定要"+config.copytxt+"吗?", function(){
                var rows = getRowIndexStr(detailNumber);
                if (rows.length==0){
                    msgWarn("明细表 "+detailNumber+" 无数据!");
                    return;
                }
                setTimeout(function(){
                    msgLoading("正在"+config.copytxt+"数据，请稍候...",1)
                },50);
                setTimeout(function(){
                    var model = getRowsDataExtraOA(detailNumber)[0];
                    for(var i=1;i<rows.length;i++){
                        var keys = Object.keys(model);
                        for(var j=0;j<keys.length;j++){
                            if (validatenull(getFieldValue(keys[j].replace("_",""),rows[i],detailNumber))&&!validatenull(model[keys[j]])){
                                setFieldValueOA(keys[j].replace("_",""),model[keys[j]],rows[i],detailNumber);
                            }
                        }
                    }
                    window.antd.message.destroy();
                    msgSuccess(config.copytxt+"完成!");
                },100);
            });
        }
        addTxtButton2(detailNumber,config.copytxt,'copy_OA'+detailNumber,width.toString(),calculateTextLength(config.copytxt)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,"anticon-copy")
    }
    if (!validatenull(config.customButtons)&&config.customButtons.length>0){
        //添加自定义按钮组部分逻辑
        setTimeout(function (){
            var width = $($($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0])).width();
            for(let i=0; i<config.customButtons.length; i++){
                const item = config.customButtons[i];
                const name = item.name;
                let title = item.title;
                const icon = item.icon;
                const ant_icon = item.ant_icon;
                width+=calculateTextLength(name)*12*1.3;
                if (!validatenull(ant_icon)){
                    width+=14;
                }
                let click = item.click;
                if (click instanceof Function){
                    if (isEmptyFunction(click)){
                        click = function unbind3(){
                            msgWarn("此按钮绑定了一个空方法!")
                        }
                        window[click.name+"_"+detailNumber+"_"+i] = click;
                    }else{
                        window[click.name+"_"+detailNumber+"_"+i] = click;
                    }
                }else if (click==null||click==undefined||click==''){
                    click = function unbind1(){
                        msgWarn("按钮未配置点击事件!")
                    }
                    window[click.name+"_"+detailNumber+"_"+i] = click;
                }else if (typeof click == 'string'){
                    if (typeof window[click]!='function'){
                        click = function unbind2(){
                            msgWarn("按钮未配置点击事件或点击事件无效!")
                        }
                        window[click.name+"_"+detailNumber+"_"+i] = click;
                    }
                }
                if (validatenull(name)&&!validatenull(icon)){
                    if (click instanceof Function){
                        $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).attr("style","min-width: "+width+"px!important;");
                        addDetailButton2(detailNumber,icon,title,click.name+"_"+detailNumber+"_"+i,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber)
                        addDetailButton(detailNumber,icon,title,click.name+"_"+detailNumber+"_"+i,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                    }else {
                        $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).attr("style","min-width: "+width+"px!important;");
                        addDetailButton2(detailNumber,icon,title,click.name+"_"+detailNumber+"_"+i,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber)
                        addDetailButton(detailNumber,icon,title,click.name+"_"+detailNumber+"_"+i,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber);
                    }
                }else if (!validatenull(name)){
                    if (validatenull(title)){
                        title = name;
                    }
                    if (click instanceof Function){
                        addTxtButton2(detailNumber,name,click.name+"_"+detailNumber+"_"+i,width,calculateTextLength(name)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,ant_icon)
                    }else{
                        addTxtButton2(detailNumber,name,click.name+"_"+detailNumber+"_"+i,width,calculateTextLength(name)*12*1.3+14,"OA_CUSTOMBUTTON_CLASS_ICON_"+detailNumber,ant_icon)
                    }
                }
            }
        },500);
    }
    if (!validatenull(config.description)){
        var isintervenor  = getUrlParamOA('isintervenor');//是否流程干预
        var ismonitor = getUrlParamOA('ismonitor');//是否流程监控
        if(ismonitor==='1'||isintervenor==='1'){
            return;//流程干预和监控不做操作
        }
        setTimeout(function (){
            var newWidth = $($($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0])).width();
            newWidth+=calculateTextLength(config.description)*12*1.3;
            var newWidth2 = $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).width();
            newWidth2+=calculateTextLength(config.description)*12*1.3;
            $($($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0])).width(newWidth);
            $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).width(newWidth2);
            setTimeout(function (){
                if ($($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).find(".detail_desc").length==0){
                    $($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]')[$('div[data-cellmark="detail_'+detailNumber+'_0_0"]').length-1]).find("div[class='detailButtonDiv']")[0]).append($("<i id='detail_desc_1"+detailNumber+"' class='detail_desc "+config.descconfig.class+"' style='"+config.descconfig.style+"'>"+config.description+"</i>"));
                }
                if ($($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).find(".detail_desc").length==0){
                    $($('div[data-cellmark="detail_'+detailNumber+'_0_0"]').find("div[class='detailButtonDiv']")[0]).append($("<i id='detail_desc_1"+detailNumber+"' class='detail_desc "+config.descconfig.class+"' style='"+config.descconfig.style+"'>"+config.description+"</i>"));
                }
            },50)
       },1000);
    }
    setTimeout(function (){
        if (!validatenull(config.buttonColspan)){
            $('div[data-cellmark="detail_'+detailNumber+'_0_0"]').parent().attr("colspan",config.buttonColspan)
        }
    },100)
}

/**
 * 禁用文件删除
 * @param filefieldname
 */
function disableFileDel(filefieldname){
    $($("div[data-fieldname=\"fj\"]").find("i[title=\"删除\"]")).hide();
}
/**
 * 禁用文件下载
 * @param filefieldname
 */
function disableFileDown(filefieldname){
    $($("div[data-fieldname=\"fj\"]").find("i[title=\"下载\"]")).hide();
}
/**
 * 禁用文件编辑
 * @param filefieldname
 */
function disableFileEdit(filefieldname){
    $($("div[data-fieldname=\"fj\"]").find("i[title=\"编辑\"]")).hide();
}

/**
 * 禁用或启用右上角按钮
 * @param title  按钮标题
 * @param isDisabled  true禁用 false启用
 */
function triggerDisableButton(title,isDisabled){
    var buttons = $('.wf-req-top-button');
    for(var i=0;i<buttons.length;i++){
        var title_ = $($('.wf-req-top-button')[i]).parent().attr('title');
        if (title==title_){
            if (isDisabled||validatenull(isDisabled)){
                $($('.wf-req-top-button')[i]).parent().attr("disabled","disabled");
                break;
            }else if (!validatenull(isDisabled)&&!isDisabled){
                $($('.wf-req-top-button')[i]).parent().removeAttr("disabled");
                break;
            }
        }
    }
}

/**
 * 指定主表字段弹出未填写提示并聚焦
 * @param column  字段如wlbm
 * @param msg 提示后缀信息
 * @param isalert  是否弹出msg提示
 */
function showTipOA(column,msg,isalert){
    if (validatenull(msg)){
        msg = "未填写";
    }
    var fieldinfo = WfForm.getFieldInfo(getFieldId(column,false));
    $("div[data-fieldname='"+column+"']").attr('tabindex','9999')
    $("div[data-fieldname='"+column+"']").focus();
    $(".prompt-box").find(".prompt-content-label").text("'"+fieldinfo.fieldlabel+"'");
    $(".prompt-box").find(".prompt-content-info").text(msg);
    //$(".prompt-box").attr("style","top:"+(126+pos.top)+"px;left:"+pos.left+"px");
    $(".prompt-box").css({
        top: $("div[data-fieldname='"+column+"']").offset().top-50,
        left: $("div[data-fieldname='"+column+"']").offset().left,
    });
    $(".prompt-box").show();
    if (isalert){
        msgError(fieldinfo.fieldlabel+msg);
    }
    setTimeout(function(){
        $(".prompt-box").hide();
        $(".prompt-box").find(".prompt-content-label").text('');
    },1500)
}
//*****************************************自定义渲染end*******************************************************//
//*****************************************常用基础数据联动start*******************************************************//
/**
 * 自动带出联系电话
 * @param sqrcol   申请人字段
 */
function setLxdh(sqrcol){
    var getLxdhId = function (){
        var lxdh = WfForm.convertFieldNameToId('lxdh','main',true);
        if (validatenull(lxdh)){
            lxdh = WfForm.convertFieldNameToId('lxfs','main',true);
        }
        if (validatenull(lxdh)){
            lxdh = WfForm.convertFieldNameToId('sjh','main',true);
        }
        if (validatenull(lxdh)){
            lxdh = WfForm.convertFieldNameToId('sj','main',true);
        }
        if (validatenull(lxdh)){
            lxdh = WfForm.convertFieldNameToId('dh','main',true);
        }
        return lxdh;
    }
    if(validatenull(sqrcol)){
        sqrcol='sqr'
    }
    var sqr = WfForm.convertFieldNameToId(sqrcol,'main',true);
    if (validatenull(sqr)){
        let pollCount = 0;
        const maxPolls = Math.ceil(8000 / 400); // 5秒转换成200毫秒的次数
        const pollInterval = setInterval(() => {
            pollCount++;
            sqr = WfForm.convertFieldNameToId(sqrcol,'main',true);
            if (!validatenull(sqr)) { // expectedValue 是你期望的值
                //clearInterval(pollInterval);
                sendSqlAsync('3T3O33OE977773O715A57OE139OAT533','hrmresource,id='+getFieldValue(sqrcol),function (data){
                    try{
                        var result = JSON.parse(data.result)
                        var dr = JSON.parse(result.data.body.data);
                        if (validatenull(dr)||validatenull(dr[0])){
                            return;
                        }
                        if (dr[0].belongto!="-1"){
                            sendSqlAsync('3T3O33OE977773O715A57OE139OAT533','hrmresource,id='+dr[0].belongto,function (data1){
                                var result1 = JSON.parse(data1.result)
                                var dr1 = JSON.parse(result1.data.body.data);
                                if (validatenull(dr1)||validatenull(dr1[0])){
                                    return;
                                }
                                setFieldValueOA(getLxdhId(),dr1[0].mobile)
                                clearInterval(pollInterval);
                            },null,true,1440);
                        }else{
                            setFieldValueOA(getLxdhId(),dr[0].mobile)
                            clearInterval(pollInterval);
                        }
                    }catch (e){
                        //console.log(e)
                        clearInterval(pollInterval);
                    }
                },null,true,1440)
            } else if (pollCount >= maxPolls) {
                clearInterval(pollInterval);
            }
        }, 400);
    }
    if (!validatenull(sqr)){
        sendSqlAsync('3T3O33OE977773O715A57OE139OAT533','hrmresource,id='+getFieldValue(sqrcol),function (data){
            try{
                var result = JSON.parse(data.result)
                var dr = JSON.parse(result.data.body.data);
                if (validatenull(dr)||validatenull(dr[0])){
                    return;
                }
                if (dr[0].belongto!="-1"){
                    sendSqlAsync('3T3O33OE977773O715A57OE139OAT533','hrmresource,id='+dr[0].belongto,function (data1){
                        var result1 = JSON.parse(data1.result)
                        var dr1 = JSON.parse(result1.data.body.data);
                        if (validatenull(dr1)||validatenull(dr1[0])){
                            return;
                        }
                        setFieldValueOA(getLxdhId(),dr1[0].mobile)
                    },null,true,1440);
                }else{
                    setFieldValueOA(getLxdhId(),dr[0].mobile)
                }
            }catch (e){
                //console.log(e)
            }
        },null,true,1440)
    }
}
//*****************************************常用基础数据联动end*******************************************************//
//*****************************************初始化方法start*******************************************************//
$(window).on('load', function(){
    //执行初始化方法...
    console.log("执行初始化方法...")
    setBlinkStyle();//设置自定义样式
    setLxdh();  //自动设置联系电话
    console.log("执行初始化方法完成")
    //执行初始化方法完成...
});
//*****************************************初始化方法end*******************************************************//

